lua-从字符串调用函数
从我在这个网站上读到的内容来看,下面的内容应该是有效的。 请一些善良的灵魂指出我哪里出了问题 我在代码中嵌入了更多的描述和打印返回,希望使阅读更容易lua-从字符串调用函数,lua,Lua,从我在这个网站上读到的内容来看,下面的内容应该是有效的。 请一些善良的灵魂指出我哪里出了问题 我在代码中嵌入了更多的描述和打印返回,希望使阅读更容易 local m = { {opt = "Solar Panels", cmd = "solarPanel"} -- There are many more options here. } function doTheMenu() print("Welcome to Spyder's Factory") print("") p
local m = {
{opt = "Solar Panels", cmd = "solarPanel"}
-- There are many more options here.
}
function doTheMenu()
print("Welcome to Spyder's Factory")
print("")
print("What would you like to make?")
local n = 1
local l = #m - 1
while true do --This while loop may or may not be relevant to the question, it's the menu
term.clear() --this is ComputerCraft lua, the term function is defined
term.setCursorPos(1,2) --elsewhere in an API
for i, j in pairs(m) do
if i == n then
if i < 10 then print(i, " ["..j.opt.."]") else print(i, " ["..j.opt.."]") end
fsel = j.cmd --set fsel to the function name I require in case of a break
tsel = j.opt --Ditto, tsel, human-friendly name
else
if i < 10 then print(i, " "..j.opt) else print(i, " "..j.opt) end
end
end
local a, b = os.pullEvent("key")
if b == 200 and n > 1 then n = n - 1 end
if b == 208 and n <= l then n = n + 1 end
if b == 28 then break end
end
write("\nSure, how many "..tsel.."? ")
qty = tonumber(read())
req[fsel] = req[fsel] + qty
str = fsel.."("..qty..")"
print("Loading function '"..fsel.."("..qty..")'") --Returns "Loading function 'solarPanel(1)'"
func = loadstring(str)
print(func) --Returns "function: 2cdfc5a7"
print("Loading function")
func() --The error line, Returns "string:1: attempt to call nil"
--tellUserWhatNeed()
--makeItHappen()
end
doTheMenu()
还有什么是术语变量,若这是所有的代码,那个么术语并没有定义,并且是空的
也就是说,要么(fsel)为零,要么fsel为零?
您确定在_G中声明了函数,并且函数名存储在fsel中吗
e、 i.在问题行打印[fsel]之前打电话,看看它能给你带来什么。这就是最终有效的解决方案:
local f = loadstring(str)
if f then
setfenv(f, getfenv())
f()
end
这将替换上面的行:
print("Loading function '"..fsel.."("..qty..")'")
func = loadstring(str)
print(func)
print("Loading function")
func()
以及添加加载函数的基本错误处理您有什么错误?顺便说一句,你可以跳过欢呼声,帖子结尾的签名被认为是错误的做法,这意味着没有名为solarPanel的全局函数。顺便说一下,请尝试发布显示错误的最小代码量。这里不需要显示用户输入的内容。term是内置API的一部分,用于显示管理ComputerCraft终端的代码。doTheMenu线更靠下。对不起,我在我原来的帖子里不清楚。我现在就把它清理掉。如果你有调试器,在你认为可能有问题的地方打印几张。错误是什么?e、 g.什么是打印加载函数“…fsel…qty…”好了,这个问题现在应该有意义了。打印行读取加载函数“solarPanel1”,我刚刚完成了“打印[fsel]”,它返回了一个空白行,它应该返回函数:。您试图调用的函数不是全局函数,不在_G中。您确定在声明solarPanel后调用的是doTheMenu吗?
print("Loading function '"..fsel.."("..qty..")'")
func = loadstring(str)
print(func)
print("Loading function")
func()