首页投稿(暂停使用,暂停投稿)程序员编程语言爱好者

Lua api(三)

2016-07-01  本文已影响1054人  AlbertS

前言#

前面我们讲了lua_getfield和lua_setfield两个api,也了解到这两个api的调用会触发table的元方法,今天我再来看两个会调用的元方法的api,这两个api同时也是一对,一个取值一个赋值,可以实现在c++中修改lua脚本中table的值。

内容#


lua_gettable##


lua_settable##


Usage##

-- 定义一个table
information = 
{
    name = "tom",
    age = 18,
    sex = "man",
}

local mt = {
    __index = function(table, key)
        print("lua --> get value --> I haven't this field : " .. key);
    end
    ,

    __newindex = function(table, key, value)
        print("lua --> set value --> I haven't this field : " .. key);
        print("lua --> but I do this : " .. key.." = "..value);
        rawset(table, key, value);
    end
}

-- 设置元表
setmetatable(information, mt);

function func_printaddr()
    print("\nlua -- > information.address : ")
    print(information.address)
end
    lua_State *L = lua_open();
    luaL_openlibs(L);

    luaL_dofile(L,"gettabletest.lua");  // 加载执行lua文件
    lua_getglobal(L,"information");     // 将全局表压入栈

    lua_pushstring(L, "age");           // 将要取的变量压入栈
    lua_gettable(L, -2);                // 取information.age的值   -->gettable用法
    if(lua_isnil(L, -1))
    {
        printf("c++ --> information.age = nil\n");
    }
    else
    {
        printf("c++ --> information.age = %d\n", lua_tointeger(L, -1));
    }
    lua_pop(L,1);                       // 弹出栈顶变量

    lua_pushstring(L, "address");       // 将要取的变量压入栈
    lua_gettable(L, -2);                // 取information.address的值
    if(lua_isnil(L, -1))
    {
        printf("\nc++ --> information.address = nil\n");
    }
    else
    {
        printf("\nc++ --> information.address = %s\n", lua_tostring(L, -1));
    }
    lua_pop(L,1);                       // 弹出栈顶变量


    lua_pushstring(L, "address");       // 将要赋值的变量压入栈
    lua_pushstring(L, "beijing");       // 将赋值的结果压入栈
    lua_settable(L, -3);                // 赋值操作                 -->settable用法

    lua_getglobal(L, "func_printaddr"); // 调用打印函数
    lua_pcall(L, 0, 0, 0);

    lua_close(L);                   //关闭lua环境  
gettable.png

总结#

上一篇 下一篇

猜你喜欢

热点阅读