Lua中在表中传递函数参数

我正在尝试编写一个类似于switch case的脚本。我的问题是我无法将参数传递到函数中。

function zerozero(input)
  return input
end

function zeroone(input)
  return input
end

function onezero(input)
  return input
end

function oneone(input)
   return input
end

local switch = {
  ['00'] = zerozero(input),
  ['01'] = zeroone(input),
  ['10'] = onezero(input),
  ['11'] = oneone(input)
 }

local first_2_bits = "00"
local input = "test"
local x = switch[first_2_bits](input)
print("x: ", x)

如果我尝试编译这个脚本,就会出现错误。问题在于它无法以这种方式将输入参数传递到函数zerozero中。你知道怎么样才能将参数传递给函数吗?非常感谢!

原文链接 https://stackoverflow.com/questions/70592115

点赞
stackoverflow用户15175264
stackoverflow用户15175264

我找到了解决方案: 只需确保您不要将参数放入表格中。表格应该像这样:

local switch = {
  ['00'] = zerozero,
  ['01'] = zeroone,
  ['10'] = onezero,
  ['11'] = oneone
 }
2022-01-05 11:38:35
stackoverflow用户2858170
stackoverflow用户2858170
# 给出以下函数

```lua
function zerozero(input)
  return input
end

function zeroone(input)
  return input
end

function onezero(input)
  return input
end

function oneone(input)
  return input
end

如果这样使用

local switch = {
  ['00'] = zerozero(input),
  ['01'] = zeroone(input),
  ['10'] = onezero(input),
  ['11'] = oneone(input)
 }

相当于使用

local switch = {
  ['00'] = input,
  ['01'] = input,
  ['10'] = input,
  ['11'] = input
 }

因此 switch['00'] 将解析为 input,在这种情况下,input 是一个字符串。 字符串无法被调用,除非你为字符串定义了一个 __call 元方法。

注意函数值和函数调用之间的区别。在这种情况下,表构造函数将对每个函数调用求值一次,并将其返回值存储在表字段中。

2022-01-05 13:43:02