Lua 中栈操作的C API示例


这是《Lua程序设计》中的例子,做个简单记录。
#include <stdio.h>
#include <lua5.2/lua.h>
#include <lua5.2/lauxlib.h>

static void stackDump(lua_State *L){
    int i;
    int top = lua_gettop(L);
    for(i = 1; i <= top; i++){
        int t = lua_type(L, i);
        switch(t){
            case LUA_TSTRING:
                printf("'%s'", lua_tostring(L, i));
                break;
            case LUA_TBOOLEAN:
                printf(lua_toboolean(L, i) ? "true":"false");
                break;
            case LUA_TNUMBER:
                printf("%g", lua_tonumber(L, i));
                break;
            default:
                printf("%s", lua_typename(L, t));
                break;
        }
        printf("  ");
    }
    printf("\n");
}

int main(void){

    lua_State *L = luaL_newstate();

    lua_pushboolean(L, 1);
    lua_pushnumber(L, 10);
    lua_pushnil(L);
    lua_pushstring(L, "vonzhou");

    stackDump(L);    // dump the stack

    lua_pushvalue(L, -4);// push the value of the index to the stack
    stackDump(L);

    lua_replace(L, 3);  // pop a value and replace the index's
    stackDump(L);

    lua_settop(L, 6);   // set the top index, fill 'nil'
    stackDump(L);

    lua_remove(L, -3);   // 
    stackDump(L);

    lua_settop(L, -5);
    stackDump(L);

    lua_close(L);
    return 0;
}
运行结果:


简单画个示意图:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值