Pour appeler une fonction dans l'espace de noms global (comme mentionné par @ THC4k) se fait facilement et ne nécessite pas loadstring()
.
x='foo'
_G[x]() -- calls foo from the global namespace
Vous devez utiliser loadstring()
(ou à pied chaque table) si la fonction dans une autre table, comme si x='math.sqrt'
.
Si vous utilisez loadstring()
, vous souhaitez non seulement ajouter une parenthèse avec l'ellipse (...)
pour autoriser les paramètres, mais également ajouter return
au premier plan.
x='math.sqrt'
print(assert(loadstring('return '..x..'(...)'))(25)) --> 5
ou marcher les tables:
function findfunction(x)
assert(type(x) == "string")
local f=_G
for v in x:gmatch("[^%.]+") do
if type(f) ~= "table" then
return nil, "looking for '"..v.."' expected table, not "..type(f)
end
f=f[v]
end
if type(f) == "function" then
return f
else
return nil, "expected function, not "..type(f)
end
end
x='math.sqrt'
print(assert(findfunction(x))(121)) -->11