按名称获取Lua函数引用

时间:2015-10-07 09:23:19

标签: string function reference lua lookup

我想通过名称作为字符串查找函数的引用:

function someFunc(a) print(a*2) end

-- I want to do something like this (I know this isn't working)
ref = _G['someFunc']

在调用脚本之前,someFunc被声明为全局函数。

我知道简单的方法是:

ref = someFunc

......但这不是我想要的。我需要通过字符串查找函数。

1 个答案:

答案 0 :(得分:0)

你一定做错了什么:

Lua 5.3.1  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> function someFunc(a) print(a*2) end
> for key,value in pairs(_G) do print(key,value) end
type    function: 0x1b8c280
rawget  function: 0x41bc70
rawlen  function: 0x41bcc0
tonumber        function: 0x41b990
_VERSION        Lua 5.3
_G      table: 0x1b8a9f0
coroutine       table: 0x1b8a7e0
load    function: 0x41c3b0
select  function: 0x41b890
debug   table: 0x1b8cf60
getmetatable    function: 0x41c530
next    function: 0x41beb0
setmetatable    function: 0x41c170
collectgarbage  function: 0x41c0a0
unpack  function: 0x424f10
print   function: 0x41bd50
ipairs  function: 0x41c300
bit32   table: 0x1b909f0
error   function: 0x41c030
loadfile        function: 0x41c4c0
arg     table: 0x1b90e80
xpcall  function: 0x41b770
tostring        function: 0x41b860
pairs   function: 0x41c2e0
rawset  function: 0x41bc20
utf8    table: 0x1b90180
require function: 0x1b8a720
math    table: 0x1b8f2d0
rawequal        function: 0x41bd10
someFunc        function: 0x1bb0160
io      table: 0x1b8d5c0
assert  function: 0x41c600
package table: 0x1b8c4a0
pcall   function: 0x41b800
loadstring      function: 0x41c3b0
module  function: 0x1b8c450
table   table: 0x1b8d2c0
string  table: 0x1b8be70
os      table: 0x1b8d040
dofile  function: 0x41c580
> _G["someFunc"]
function: 0x1bb0160
> _G['someFunc']
function: 0x1bb0160