1
votes

I have this Lua code to initialize a table:

table = {
  a = 1;
  b = myfunc();
  c = function () <some code> end;
}

After this table.c has type function and I have to use table.c() in a print statement with the .. operator to get the result. But I would like to just use table.c instead.

Is there a way that I can get the return value of the function assigned to table.c so the type is not function without having to define a function outside of the table?

1

1 Answers

2
votes

If you wanted table.c to contain the return value of the function, then you should have assigned it the return value of the function. You instead assigned it the function itself.

To get the return value of a function, you must call that function. It's really no different from b. myfunc is a function; myfunc() is calling that function and storing its return value.

But, due to Lua's grammar, calling a function that you are defining requires that you need to wrap the function constructing expression in (), then call it:

c = (function () <some code> end)();

This of course will only contain the value of that function at the time that the table is constructed.