跟着 Lua 5.1 官方参考文档学习 Lua (4)

2.7 – Error Handling

Because Lua is an embedded extension language, all Lua actions start from C code in the host program calling a function from the Lua library (see lua_pcall). Whenever an error occurs during Lua compilation or execution, control returns to C, which can take appropriate measures (such as printing an error message).

Lua code can explicitly generate an error by calling the error function. If you need to catch errors in Lua, you can use the pcall function.

例子:使用 lua_call 调用 Lua 函数

#include <stdio.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main() {
   
   
    lua_State *L = luaL_newstate();  // 创建一个新的 Lua 状态机
    luaL_openlibs(L);  // 打开 Lua 标准库

    // Lua 脚本代码,定义一个简单的函数,产生错误
    const char *script = 
        "function foo() \n"
        "   error('test error')\n"
        "end\n";

    // 加载并执行 Lua 脚本
    if (luaL_dostring(L, script) != LUA_OK) {
   
   
        printf("Error loading script: %s\n", lua_tostring(L, -1));
        lua_close(L);
        return 1;
    }

    // 调用 Lua 函数,并处理错误
    lua_getglobal(L, "foo");

    // 使用 lua_call,如果出现错误,会直接终止进程
    lua_call(L, 0, 0);

    lua_close(L);  // 关闭 Lua 状态机
    return 0;
}

输出

PANIC: unprotected error in call to Lua API ([string "function foo() ..."]:2: test error)

出现错误会直接终止进程

例子:使用 lua_pcall 调用 Lua 函数

#include <stdio.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main() {
   
   
    lua_State *L = luaL_newstate();  // 创建一个新的 Lua 状态机
    luaL_openlibs(L);  // 打开 Lua 标准库

    // Lua 脚本代码,定义一个简单的函数,产生错误
    const char *script = 
        "function foo() \n"
        "   error('test error')\n"
        "end\n";

    // 加载并执行 Lua 脚本
    if (luaL_dostring(L, script) != LUA_OK) {
   
   
        printf("Error loading script: %s\n", lua_tostring(L, -1));
        lua_close(L);
        return 1;
    }

    // 调用 Lua 函数,并处理错误
    lua_getglobal(L, "foo");

    int ret = lua_pcall(L, 0, 0, 0);
    if (ret != LUA_OK) {
   
   
        // 如果发生错误,打印错误信息
        printf("Error occurred: %s\n", lua_tostring(L, -1));
    }

    lua_close(L);  // 关闭 Lua 状态机
    return 0;
}

输出

Error occurred: [string "function foo() ..."]:2: test error

例子:使用 lua_pcall,自定义错误处理函数

#include <stdio.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

// 错误处理函数
int my_error_handler(lua_State *L) {
   
   
    const char *msg = lua_tostring(L, -1);  // 获取错误信息
    printf("Error in Lua code: %s\n", msg);  // 输出错误信息
    lua_pushliteral(L, "Error handled in my_error_handler");
    return 1;  // 返回 1,返回新的错误消息
}

int main() {
   
   
    lua_State *L = luaL_newstate();  // 创建一个新的 Lua 状态机
    luaL_openlibs(L);  // 打开 Lua 标准库

    // 将错误处理函数压入栈中
    lua_pushcfunction(L, my_error_handler);

    // 定义 Lua 脚本,故意写一个错误的脚本(调用了未定义的函数 'foo')
    const char *script = 
        "foo()  -- 这是一个错误,foo 未定义\n";

    if (luaL_loadstring(L, script) != 0) {
   
   
        printf("load error!\n");
        return 1;
    }

    // 使用 lua_pcall 执行 Lua 代码,并指定错误处理函数
    int ret = lua_pcall(L, 0, 0, -2);  // 执行 Lua 代码
    if (ret != LUA_OK) {
   
   
        // 如果发生错误,错误处理函数会将错误信息入栈
        printf("error msg: %s\n", lua_tostring(L, -1));
    }

    lua_close(L);  // 关闭 Lua 状态机
    return 0;
}

输出

Error in Lua code: [string "foo()  -- 这是一个错误,foo 未定义..."]:1: attempt to call global 'foo' (a nil value)
error msg: Error handled in my_error_handler

注意:error() 函数可以返回任意的值,并不是只能返回字符串。

2.8 – Metatables

Every value in Lua can have a metatable. This metatable is an ordinary Lua table that defines the behavior of the original value under certain special operations. You can change several aspects of the behavior of operations over a value by setting specific fields in its metatable.

For instance, when a non-numeric value is the operand of an addition, Lua checks for a function in the field "__add"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值