Anish
Anish

Reputation: 1498

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

Upvotes: 1

Views: 2953

Answers (2)

Jay Rajput
Jay Rajput

Reputation: 1888

This is described as a common beginner mistake in the book 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 Programming in Lua for other person who visit this question.

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"

Upvotes: 1

lhf
lhf

Reputation: 72312

You want

fn = ft[index]

because

fn = ft.index

is equivalent to

fn = ft["index"]

Upvotes: 3

Related Questions