Lua代码运行报string.find参数预期字符串得到函数,如何排查?
错误原因
- 核心报错触发原因:你在给
location变量赋值时,直接写了local location = io.read,没有加括号调用io.read函数。io.read本身是Lua的标准输入读取函数,不加括号的话赋值的是函数本身,而不是函数执行后返回的用户输入字符串,因此string.find收到的第一个参数是函数类型,不符合预期的字符串类型,触发报错。 - 隐藏待修正问题:你代码中判断非空时用的
nul是错误写法,Lua的空值关键字为nil,不修正的话后续运行会触发全局变量未定义的报错。
修正后的代码
输入赋值部分
print(" Do you go to the quest location") local location = io.read() -- 加括号调用函数,获取用户输入的字符串
逻辑判断部分
if (string.find(location,patternno2) ~= nil) then -- 替换nul为Lua原生空值关键字nil print(" You decide that you will live your life as a hermit, alone and isolated. GAME OVER") return end local patternyes2 = '^[yY][eE]?[sS]?$' if (string.find(location,patternyes2) ~= nil) then -- 替换nul为Lua原生空值关键字nil print(" Great! You leave for the land of Yore.") print("You arrive at the castle of the previously mentioned king.") end
内容的提问来源于stack exchange,提问作者Wiggitywy
相关产品推荐
相关产品推荐

