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

使用Fengari从Lua调用JavaScript函数时参数传递异常

解决Fengari中Lua调用JavaScript函数参数为undefined的问题

问题出在Fengari的Lua-JS交互机制上:直接将JavaScript函数推入Lua环境后,Lua调用该函数时,不会自动把Lua参数转换为JavaScript原生值,且函数接收的并非Lua传入的目标参数。

修正方法是给JavaScript函数套一层包装,手动从Lua栈中读取并转换参数:

const lua = fengari.lua;
const lauxlib = fengari.lauxlib;
const lualib = fengari.lualib;
const interop = fengari.interop;

function display(digit) {
    console.log(`digit is ${digit}`);
}

let L = lauxlib.luaL_newstate();
lualib.luaL_openlibs(L);
interop.luaopen_js(L);

// 包装函数:负责从Lua栈读取参数并转换为JS类型
interop.push(L, function(L) {
    // 读取Lua传入的第一个参数(栈索引为1),转换为JS值
    const jsDigit = interop.tojs(L, 1);
    display(jsDigit);
});
lua.lua_setglobal(L, fengari.to_luastring("display"));

const result = lauxlib.luaL_dostring(L, fengari.to_luastring('display(64)'));

if (result !== lua.LUA_OK) {
    const errorMessage = lua.lua_tostring(L, -1);
    console.error("Lua error:", fengari.to_jsstring(errorMessage));
    lua.lua_pop(L, 1);
} else {
    console.log("Lua code executed successfully");
}

说明

  • 包装函数的第一个参数是Lua状态机L,通过它可以访问Lua栈中的参数。
  • 使用interop.tojs(L, 1)将Lua栈中索引为1的参数(即Lua调用时传入的64)转换为JavaScript原生数值,再传递给原display函数。
  • 修改后调用display(64),就能正确输出digit is 64。

内容的提问来源于stack exchange,提问作者Guy J Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 03:57:27