Lua 尝试返回多个值,attempt to compare nil with number



 --[[
s,e=string.find("hello Lua users","Lua")
print(s,e)
--]]

function maximum (a)
   local mi = l
   local m = a[mi]
   for i,val in ipairs(a) do
      if val > m then
         mi = i
         m = val
      end
   end
   return m,mi  
end

print(maximum({8,10,23,12,5}))

报错:
Exception in thread "main" com.naef.jnlua.LuaRuntimeException: ...\ldt\workspace\test\src\5.1return multiple value.lua:10: attempt to compare nil with number at com.naef.jnlua.LuaState.lua_pcall(Native Method) at com.naef.jnlua.LuaState.call(LuaState.java:555) at org.eclipse.koneki.ldt.support.lua51.internal.interpreter.JNLua51Launcher.run(JNLua51Launcher.java:128) at org.eclipse.koneki.ldt.support.lua51.internal.interpreter.JNLua51Launcher.main(JNLua51Launcher.java:143)

lua

战场原荡漾 10 years, 3 months ago

如果我没看错的话,题主你写的程序的第四行是mi = l而不是mi = 1吧,把l改成1就好了吧…

Anstsa answered 10 years, 3 months ago


 local mi = l

这个 l 是哪来的? l是空值
因此你的下一句


 local m = a[mi]

导致m为nil值。

变量只能同类型比较
因此会使得


 if val > m then

这句报错。

下降气流君 answered 10 years, 3 months ago

Your Answer