只是使用
luaL_tolstring
得到任何东西的字符串表示。这也尊重
__tostring
std::string_view
#include <iostream>
#include <string_view>
#include <lua.hpp>
void poststring(std::string_view sv) { std::cout << sv << '\n'; }
void endpost() { std::cout << "---\n"; }
int l_my_print(lua_State *L) {
int nargs = lua_gettop(L);
for (int i = 1; i <= nargs; ++i) {
poststring(luaL_tolstring(L, i, nullptr));
lua_pop(L, 1); // remove the string
}
endpost();
return 0;
}
int main() {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, l_my_print);
lua_setglobal(L, "my_print");
int i = 0;
lua_pushlightuserdata(L, &i);
lua_setglobal(L, "udata");
luaL_dostring(L, "my_print(1, 3.14, \"Hello World\")\n"
"my_print(false, udata, {})\n");
lua_close(L);
}
调用示例:
$ clang++ -Wall -Wextra -Wpedantic -std=c++17 -I/usr/include/lua5.3 test.cpp -llua5.3
$ ./a.out
1
3.14
Hello World
---
false
userdata: 0x7fff4685993c
table: 0x883300
---