如何在C ++中访问package.preload中的局部变量

时间:2018-07-19 08:08:51

标签: c++ lua

以下代码可以正常工作,并且可以按预期打印3

#include <lua.hpp>
#include <ctime>
#include <chrono>

void main()
{
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    lua_settop(L, 0);
    //Script A
    luaL_dostring(L, "package.preload['A'] = function () local A = {}\n"
                     "A.num = 3\n"
                     "return A end");
    //Script B
    luaL_dostring(L, "local A = require 'A' print(A.num)");
    lua_close(L);
}

但是我想在C ++中获得A.num的值。

我尝试了以下代码,但没有显示A.num

lua_getglobal(L, "require");
lua_pushstring(L, "A");
if (lua_pcall(L, 1, LUA_MULTRET, 0) != 0) 
{
    std::cerr << "lua:" << lua_tostring(L, 1) << '\n';
    lua_pop(L,1);
}
lua_getglobal(L, "num");
if (lua_type(L, -1) == LUA_TNUMBER)
    std::cout << "A.num : " << lua_tonumber(L, -1) << std::endl;
lua_pop(L, 1);

如何正确获取A.numC++的值?

1 个答案:

答案 0 :(得分:2)

require 'A'返回一个表。这意味着您必须使用lua_getfield而不是lua_getglobal

#include <iostream>

#include <lua.hpp>

int main() {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    luaL_dostring(L, "package.preload['A'] = function () local A = {}\n"
                     "A.num = 3\n"
                     "return A end");

    lua_getglobal(L, "require");
    lua_pushstring(L, "A");
    if (lua_pcall(L, 1, LUA_MULTRET, 0) != 0) {
        std::cerr << "lua:" << lua_tostring(L, 1) << '\n';
        lua_pop(L, 1);
    }
    lua_getfield(L, -1, "num");
    int isnum;
    double num = lua_tonumberx(L, -1, &isnum);
    if (isnum == 1) {
        std::cout << "A.num = " << num << '\n';
    } else {
        std::cerr << "Field 'A.num' is not a number\n";
    }
    lua_pop(L, 1); // pop 'num'
    lua_pop(L, 1); // pop 'A'

    lua_close(L);
}

这两个lua_pop(L, 1)当然可以合并为一个lua_pop(L, 2)