lua中的多行函数表

时间:2015-06-04 11:03:53

标签: lua

我似乎无法找到有关创建包含多行函数的表的任何其他在线帮助。例如,这是来自lua wiki的代码片段。

action = {
  [1] = function (x) print(1) end,
  [2] = function (x) z = 5 end,
  ["nop"] = function (x) print(math.random()) end,
  ["my name"] = function (x) print("fred") end,
}

我想做这样的事情:

action = {
[1] = function blah()
more code here
end

[2] = function blahblah()
more code here
end

}

那我怎么能这样做呢?

2 个答案:

答案 0 :(得分:4)

List<String> stringValues = new ArrayList<String>();
for (ComplexObj value : map.values()) {
    stringValues.add(value.getDesiredStringValueGetterMethodIfYouUseBeanSyntax());
}

你可以自由地做到这一点。

答案 1 :(得分:0)

当使用 [[]] 作为数据类型字符串时,您几乎可以在 Lua 中存储所有带有缩进的源代码。
示例

return {cat=[[return function(cat)
for line in io.lines(cat) do
 io.write(string.format('%s\n',line)):flush()
end 
end]],
chknx=[[-- chknx()
return function(func,...)
 local rc,rs=pcall(assert,func)
 if rc then return func(...) else return rc,rs end
end]],
cls=[[-- cls()
return function()
 os.execute('env -i TERM="xterm-256color" clear')
end]],
free=[[-- free()
return function()
local a=(collectgarbage('count')*1024)
print('Before: '..a..' Byte')
collectgarbage()
print('After: '..(collectgarbage('count')*1024)..' Byte')
a=a-collectgarbage('count')*1024
print('Freed: '..a..' Byte')
return a
end]],
shell=[[-- shell()
return function(shell)
if (type(shell)=='string') then
 os.execute(shell)
else
 os.execute('${SHELL} -l')
end
end]]}

这是一个带字符串的表格。
所以每个函数都可以通过:funcname=load(string,'My Function')()
发生错误时,字符串“My Function”用于回溯;-)