lualua-table

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


I am ( lua newbie/3days) trying to call a function stored inside a lua table as in following code

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 

I am getting the error attempt to call local 'fn' (a nil value) The name funct gets printed in both say calls.

Thanks


Solution

  • You want

    fn = ft[index]
    

    because

    fn = ft.index
    

    is equivalent to

    fn = ft["index"]