Error while trying to call a class method: attempt to index local 'self' (a nil value) - Lua

£可爱£侵袭症+ 提交于 2019-12-31 03:27:10

问题


I'm creating a lua script that should run on the TI-Nspire calculator. The problem is that while running my script I get the error Attempt to index local 'self' (a nil value) when the button:activate() method is called. The parser says the error is in the 8th line in the code below. The problematic code is as follows:

button = class(view)

function button:init()
    self.selected = false
end

function button:activate()
    self.selected = true
end

I call the activate function like this:

item = button()
local action = "activate"
local arguments = {}
item[action](unpack(arguments))

I am aware the class() function doesn't exist in "stock" Lua, it's a function available in the TI-Nspire Lua implementation. You can find its definition and usage here.


回答1:


obj:methodname(args) is sugar for obj.methodname(obj,args). So, if you want to use the syntax item[action](unpack(arguments)), you need to use item[action](item,unpack(arguments)). Otherwise, try item:activate(unpack(arguments)) if you can use method explicitly.



来源:https://stackoverflow.com/questions/7353035/error-while-trying-to-call-a-class-method-attempt-to-index-local-self-a-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!