尝试调用类方法时出错:尝试索引本地“self"(一个 nil 值)-Lua [英] Error while trying to call a class method: attempt to index local 'self' (a nil value) - Lua
问题描述
我正在创建一个应该在 TI-Nspire 计算器上运行的 lua 脚本.问题是,在运行我的脚本时,当调用 button:activate()
方法时,我收到错误 Attempt to index local 'self' (a nil value)
.解析器说错误在下面代码的第 8 行.有问题的代码如下:
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
我这样调用 activate 函数:
I call the activate function like this:
item = button()
local action = "activate"
local arguments = {}
item[action](unpack(arguments))
我知道stock"Lua 中不存在 class()
函数,它是 TI-Nspire Lua 实现中可用的函数.您可以在此处找到它的定义和用法.
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.
推荐答案
obj:methodname(args)
是 obj.methodname(obj,args)
的糖.所以,如果你想使用语法item[action](unpack(arguments))
,你需要使用item[action](item,unpack(arguments))
.否则,如果可以显式使用方法,请尝试 item:activate(unpack(arguments))
.
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.
这篇关于尝试调用类方法时出错:尝试索引本地“self"(一个 nil 值)-Lua的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!