5

作为初学者,我在 Lua 中有一个简单的问题:

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

b = {125, 116, a()}

   print(b[1])

它应该只打印125,但也打印hello。即使未选择表值。

4

2 回答 2

6

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.

于 2013-10-05T22:50:53.880 回答
5

删除括号应该让它工作:(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])

否则,您将用三个值填充表格:

  • 125,

  • 116

  • 以及函数调用'a()'的返回值。

于 2013-10-05T21:46:01.087 回答