Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

lua - How do I add a method to the table type?

How do I add a method to the table type? I'm trying to write a method that searches through the values of a table. So far I have.

function table:contains(value)
  for _, v in ipairs(self) do
    if v == value then return true end
  end
  return false
end

Yet when I try to do the following.

t = {'four', 'five', 'six'}
t:contains('five')

I get the error.

stdin:1: attempt to call method 'contains' (a nil value)

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As was said by others, your t is a simple table, it contains only the following key-value pairs: [1]='four', [2]='five', [3]='six'.

If you want to "extend" the t to be able to access functions from the table module, you have to set a metatable with __index pointing to the table module. I use the following function to access it easily:

function T(t)
    return setmetatable(t, {__index = table})
end

You can then use it as follows (thanks to syntax sugar no parentheses needed):

t = T{'four', 'five', 'six'}
t:insert('seven')
print(t:contains('seven')) --> true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...