将一些数据推送到 Lua 调用函数
Push some data to Lua call function
我有两个文件 - 一个用于执行Lua脚本和脚本本身。
他们在这里:
主机.cpp:
#include <lua.hpp>
#include <iostream>
using namespace std;
int someHandler(lua_State *l)
{
int argc = lua_gettop(l);
for (int i = 0; i < argc; i++)
{
cout << "ARG[" << i + 1 << "] = " << lua_tostring(l, i + 1) << endl;
}
lua_pushstring(l, "m_pi");
//lua_pop(l, argc - 1);
//lua_pushnumber(l, 3.14);
return argc;
}
int main()
{
lua_State *l = lua_open();
luaL_openlibs(l);
lua_register(l, "moo", someHandler);
luaL_dofile(l, "script.lua");
lua_close(l);
return 0;
}
脚本.lua:
res = moo("hello", "world");
print(moo());
for k, v in res do
print(k.." = "..v);
end
编译host.cpp
与g++ host.cpp -o host.elf -I/usr/include/lua5.1 -llua5.1
.
运行host.elf
的结果是:
ARG[1] = hello
ARG[2] = world
<n>
虽然它应该是:
ARG[1] = hello
ARG[2] = world
m_pi
我做错了什么?
逐行说明:
--This calls moo with two arguments
--(ignore the assignment for now, we will come back to that)
res = moo("hello", "world");
控制权转移到C++:
//the stack of l looks like this: ["hello", "world"]
int someHandler(lua_State *l)
{
int argc = lua_gettop(l); //int argc = 2;
//This loop prints:
//"ARG[1] = hellon"
//"ARG[2] = worldn"
for (int i = 0; i < argc; i++)
{
cout << "ARG[" << i + 1 << "] = " << lua_tostring(l, i + 1) << endl;
}
//This pushes "m_pi" on to the stack:
lua_pushstring(l, "m_pi");
//The stack now looks like ["hello", "world", "m_pi"]
//Returns 2.
//Lua will treat this as a function which
//returns the top two elements on the stack (["world", "m_pi"])
return argc;
}
控制返回到 lua:
--Assigns the first result ("world") to res, discards the other results ("m_pi")
res = moo("hello", "world");
--Calls `moo` with zero arguments.
--This time, `lua_gettop(l)` will evaluate to `0`,
--so the for loop will not be entered,
--and the number of results will be taken to be `0`.
--The string pushed by `lua_pushstring(l, "m_pi")` will be discarded.
--`moo()` returns no results, so `print` prints nothing.
print(moo());
--WTF??: res = "world", which is a string, not an expression which evaluates to
--a loop function, a state variable, and a element variable.
--The for loop will raise in an error when it
--attempts to call a copy of `res` (a string)
for k, v in res do
print(k.." = "..v);
end
相关文章:
- 调用 lua 函数的地址为 C/C++?
- 如何在C++中获取lua函数作为参数,然后调用它
- C++-在没有自定义.lib文件的情况下从Lua C模块调用Lua函数
- Lua C API 自定义打印函数,在字符串中传递空格时不调用
- 如何在 lua cpp 模块中调用托管 c++ dll 函数
- C++调用lua_dostring来加载具有"require('cjson')"的Lua Scrip引发错误:cjson.so:未定义的符号:lua_getfield
- 使用二进制参数调用LUA方法
- 从 LUA 脚本调用类函数C++
- 从C++调用 Python 或 Lua 来计算表达式,仅在需要时计算未知变量
- 如何安全地从 Lua 调用C++函数
- 从c++调用lua函数时,如何使表和变量值保持不变
- Lua OOP函数没有被调用
- 在从 Lua 调用的C++中,lua_type(L,0) 返回未记录的 9
- C++ - 调用 Lua 函数始终返回 0
- 从C++调用 lua 函数时"Error in error handling"
- C++-Lua:获取调用方表名
- Lua errorPANIC:调用 Lua API 时出现不受保护的错误(尝试调用 nil 值)
- 从Lua调用C ++函数传递的参数较少
- 将一些数据推送到 Lua 调用函数
- 表作为从Lua调用的C函数的参数