我是(lua newbie / 3days)尝试调用存储在lua表中的函数,如下面的代码
function sayhello()
return "hello";
end
function saygoodbye()
return "goodbye";
end
funct = {
["1"] = sayhello,
["2"] = saygoodbye,
["name"] = "funct"
};
function say(ft,index)
local name = ft.name;
print("\nName : " .. name .. "\n");
local fn = ft.index;
fn();
end
say(funct,"1"); -- attempt to call local 'fn' (a nil value)
say(funct,"2"); -- attempt to call local 'fn' (a nil value)
-- the Name funct prints in both cases
我收到错误尝试致电本地' fn' (零值) 名称funct在两个电话中打印出来。
由于
答案 0 :(得分:3)
你想要
fn = ft[index]
,因为
fn = ft.index
相当于
fn = ft["index"]
答案 1 :(得分:1)
这被描述为书Programming in Lua中常见的初学者错误。如果你犯了错误,你知道你已经开始学习了。 @lhf的答案是正确的,但我只是想为其他访问此问题的人强调一本精彩的书[Lua中的Praogramming](https://www.lua.org/pil/2.5.html)。
初学者的常见错误是将a.x与[x]混淆。首先 form表示[" x"],即由字符串" x"索引的表。 第二种形式是由变量x的值索引的表。看到 差异:
a = {} x = "y" a[x] = 10 -- put 10 in field "y" print(a[x]) --> 10 -- value of field "y" print(a.x) --> nil -- value of field "x" (undefined) print(a.y) --> 10 -- value of field "y"