You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从C调用Lua 5.2函数触发LUA_ERRRUN错误,求排查方案

问题排查与修复

你的代码里存在几个关键问题,导致了LUA_ERRRUN错误,以下是具体排查思路和修复方案:

1. 未执行加载的Lua代码块

luaL_loadfile仅将Lua文件编译为字节码并压入栈中,但没有执行这段代码,因此Lua文件里定义的hello全局函数并未被注册到Lua环境中。此时调用lua_getglobal根本找不到hello函数。

修复:在luaL_loadfile成功后,先执行一次lua_pcall来运行加载的代码块:

status = luaL_loadfile(L, "play.lua");
if (status != LUA_OK) {
    fprintf(stderr, "Could not load 'play.lua'!\n");
    exit(1);
}
// 执行加载的Lua代码,注册hello函数
result = lua_pcall(L, 0, 0, 0);
if (result != LUA_OK) {
    fprintf(stderr, "Error executing play.lua: %s\n", lua_tostring(L, -1));
    exit(1);
}

2. 函数存在性判断逻辑完全颠倒

代码中:

lua_getglobal(L, "hello");
if (lua_isfunction(L, -1)) {
    fprintf(stderr, "ERROR: Not a function!\n");
    exit(1);
}

这段逻辑是如果找到的是函数,就报错退出,完全搞反了。正确的逻辑应该是:如果栈顶不是函数,才报错:

lua_getglobal(L, "hello");
if (!lua_isfunction(L, -1)) { // 加!取反修正逻辑
    fprintf(stderr, "ERROR: 'hello' is not a function!\n");
    exit(1);
}

3. 拼写错误导致的输出异常

代码中fprintf(sterr, ...)里的sterr是笔误,应该是stderr,这个错误会导致编译警告,甚至运行时无法正确输出错误信息。

修复后的完整C代码

#include <stdio.h>
#include <stdlib.h>

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"


int
main(void) {
    lua_State *L;
    int status;
    int result;

    L = luaL_newstate();
    luaL_openlibs(L);

    status = luaL_loadfile(L, "play.lua");
    if (status != LUA_OK) {
        fprintf(stderr, "Could not load 'play.lua'!\n");
        exit(1);
    }

    // 先执行Lua代码,注册全局函数
    result = lua_pcall(L, 0, 0, 0);
    if (result != LUA_OK) {
        fprintf(stderr, "Error executing play.lua: %s\n", lua_tostring(L, -1));
        exit(1);
    }

    lua_getglobal(L, "hello");
    if (!lua_isfunction(L, -1)) {
        fprintf(stderr, "ERROR: 'hello' is not a function!\n");
        exit(1);
    }

    result = lua_pcall(L, 0, 0, 0);
    if (result != LUA_OK) {
        fprintf(stderr, "Error running hello(): %s\n", lua_tostring(L, -1));
        exit(1);
    }
    fprintf(stdout, "lua ran fine\n");

    lua_close(L);
    return 0;
}

另外,建议在处理Lua错误时,使用lua_tostring(L, -1)获取具体的错误描述,而不是只输出错误码,这样能更快定位问题。

内容的提问来源于stack exchange,提问作者kollie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 01:47:29