Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the function in table is called even if it's not selected

Tags:

lua

lua-table

As a beginner I have a kind of simple problem in Lua:

a = function()
   print("hello")
end

b = {125, 116, a()}

   print(b[1])

it should only print 125, but also prints hello too. even if table value is not selected.

like image 449
Vitalijus Sivakovas Avatar asked Oct 05 '13 21:10

Vitalijus Sivakovas


2 Answers

As written, you have created a function that you assigned to a that takes no arguments and returns nothing; it has the side effect of printing "hello".

You then create a table stored in b that has three expressions: b[1] and b[2] are numbers, and b[3] is the result of calling the function stored in a, which will be adjusted by the usual rules to a single value by padding as required with nil. So b will be a table containing only two entries, both numbers. However, a() was called while creating b's value, which printed "hello".

Finally, you call print(b[1]) which prints the expected number.

That fully explains the output you saw. Since that is likely not the output you expected to see, you can fix this in several ways.

For example, declare a to return "hello" instead of calling print.

a = function() return "hello" end

Then calling it while constructing the table stored in b will not print anything, and b will get a third element, the string "hello".

Alternatively, you can store the function as written in b by leaving off the parenthesis that caused it to be called.

b = {125, 116, a}

Again, b holds a table that is a sequence of three elements. In this case, b[3] is the function that prints "hello".

Which you choose to do depends entirely on your intended use for the values stored in the table in b.

like image 59
RBerteig Avatar answered Oct 15 '22 16:10

RBerteig


Removing the parentheses should get it to work: (live @ codepad.org):

a = function()
   print("hello")
end

--[[ Previous code:
  'a()' will execute the function 'a' and will evaluate to its return value
  b = {125, 116, a()}
]]

-- a is now a reference to the function (you could execute it by using: 'b[3]()')
b = {125, 116, a}

print(b[1])

Otherwise you're filling your table with three values:

  • 125,

  • 116

  • and the return value of the function call 'a()'.

like image 33
ComFreek Avatar answered Oct 15 '22 15:10

ComFreek