lua 例子

//顶 -1 -2 -3
//顶 3  2  1

#include <stdio.h>
#include <string.h>
extern "C"{
    #include <lua.h>
    #include <lauxlib.h>
    #include <lualib.h>
}
#pragma comment(lib,"lua.lib") 

void stackDump(lua_State* L)
{
    int i;
    int top = lua_gettop(L); //lua_gettop返回堆栈中的元素个数
    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;
        }
    }
}

int main()
{
    lua_State* L = luaL_newstate();
    lua_pushboolean(L, 1);//true
    lua_pushnumber(L, 10);// true 10
    lua_pushnil(L);// true 10 nil
    lua_pushstring(L, "HELLO");//true 10 nil HELLO 
    stackDump(L);

    lua_pushvalue(L, -4);//true 10 nil HELLO true
    stackDump(L);

    //lua_replace从栈顶弹出元素值并将其设置到指定索引位置
    lua_replace(L, 3); //true 10 true  HELLO 
    stackDump(L);

    lua_settop(L, 6);//true 10 true  HELLO nil nil   lua_settop设置栈顶(也就是堆栈中的元素个数)为一个指定的值
    stackDump(L);

    lua_remove(L, -3);//true 10 true nil nil       lua_remove移除指定索引位置的元素
    stackDump(L);

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

    lua_close(L);

    return 0;
}
原文地址:https://www.cnblogs.com/zzyoucan/p/5922471.html