【发布时间】:2015-07-16 01:20:07
【问题描述】:
我正在尝试创建一个函数来检查一个元素是否已经在一个数组中,但是我在将一个表传递给一个冒号函数时遇到了问题。以下代码给了我错误“尝试调用方法'inTable'(一个零值)”:
function main()
test = {1,2}
if test:inTable(1) then
print("working")
else
print("not working")
end
end
--Checks to see if an element is in a table
function table:inTable(element)
--Go through each element of the table
for i in pairs(self) do
--If the current element we are checking matches the search string, then the table contains the element
if self[i] == element then
return true
end
end
--If we've gone through the whole list and haven't found a match, then the table does not contain the element
return false
end
如果我更改它以便调用“inTable(test, 1)”而不是“test:inTable(1)”并将函数定义更改为“function inTable(self, element)”,则此操作正常。我不确定为什么在这里使用冒号函数不起作用。
【问题讨论】:
-
我也花了一段时间才理解“test:inTable(1)”和“table.inTable(test, 1)”之间的区别。我已经记录了我分析这种差异的步骤here——也许它会有所帮助。
标签: lua