如何从 lua 异常中获取数据?

如何从 lua 异常中以表格形式获取数据?

x * 2

-- stdin:1: attempt to perform arithmetic on a nil value (global 'x')
-- stack traceback:
--         stdin:1: in main chunk
--         [C]: in ?

如何从异常中获取信息?下面是一个例子

print(getErrorInfo()['message'])
print(getErrorInfo()['line'])

-- attempt to perform arithmetic on a nil value (global 'x')
-- 1

原文链接 https://stackoverflow.com/questions/70905075

点赞
stackoverflow用户1847592
stackoverflow用户1847592

你必须解析错误消息

local function func_to_call() x = x*2 end

local ok, err_obj = pcall(func_to_call)
if not ok then
  local line_no, err_mes = tostring(err_obj):match":(%d+): (.*)"
  local err_info = {message = err_mes, line = tonumber(line_no)}
  print(err_info.line, err_info.message)
end
2022-01-29 13:44:04