在 Lua 中,如何使用 table 索引调用存储在 table 中的函数?

In Lua, how to call a function stored inside a table using the table index?

我(lua newbie/3days)正在尝试调用存储在 lua table 中的函数,如下面的代码

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 

我收到错误 attempt to call local 'fn' (nil value) name 函数在两个 say 调用中都被打印出来。

谢谢

你想要

fn = ft[index]

因为

fn = ft.index

等同于

fn = ft["index"]

对于访问此问题的其他人,这在书中被描述为初学者常见的错误 Programming in Lua. If you make mistakes, you know that you have started learning. The answer by @lhf is correct, but I just wanted to highlight the wonderful book [Praogramming in Lua] (https://www.lua.org/pil/2.5.html)。

A common mistake for beginners is to confuse a.x with a[x]. The first form represents a["x"], that is, a table indexed by the string "x". The second form is a table indexed by the value of the variable x. See the difference:

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"