zoukankan      html  css  js  c++  java
  • lua例子(进出栈)

    #include <stdio.h>
    extern "C"
    {
    #include "lua-5.2.2/src/lauxlib.h"
    #include "lua-5.2.2/src/lualib.h"
    #include "lua-5.2.2/src/lstate.h"
    }
    //lua与c交互栈的索引,假如栈中有5个元素
    //5 -1
    //4 -2
    //3 -3
    //2 -4
    //1 -5
    void stackDump(lua_State* L)
    {
        int i = 0;
        int top = lua_gettop(L);//获取栈中元素的个数,即栈顶元素的索引
        for (int i = 0; i < top; i++)
        {
            int t = lua_type(L, i);//返回栈中元素的类型
            switch (t)
            {
            case LUA_TSTRING:
                printf("%s", lua_tostring(L, i));//从栈中i索引位置取字符串,返回字符串的指针,对于字符串指针不能在函数外部,函数返回后会清理栈
                break;
            case LUA_TBOOLEAN:  /* booleans */ 
                printf(lua_toboolean(L, i) ? "true" : "false"); 
                break;
            case LUA_TNUMBER:  /* numbers */ 
                printf("%g", lua_tonumber(L, i)); 
                break;
            default:  /* other values */ 
                printf("%s", lua_typename(L, t));//转换类型码到类型名
                break;
            }
            printf("  ");
        }
        //printf("
    ");
    }
    
    
    int main()
    {
        lua_State* L = luaL_newstate();
        lua_pushboolean(L, 1);//向栈中压入bool类型
        lua_pushinteger(L, 10);//向栈中压入int类型
        lua_pushnil(L); //向栈中压入空值nil
        lua_pushstring(L, "hello");//压入c风格字符串
        stackDump(L); 
        /* true  10  nil  `hello'  */ 
    
        lua_pushvalue(L, -4); //压入堆栈上指定索引位置的拷贝到栈顶
        stackDump(L); 
        ///* true  10  nil  `hello'  true  */ 
    
        lua_replace(L, 3); 
        stackDump(L); 
        ///* true  10  true  `hello'  */ 
        /*Lua_insert移动栈顶元素到指定索引位置*/
        lua_settop(L, 6); //设置栈顶,不够补nil,多了删除,lua_settop(L, 0)清空栈
        stackDump(L); 
        ///* true  10  true  `hello'  nil  nil  */ 
    
        lua_remove(L, -3);//移除指定索引位置的元素,并将上面的元素下移
        stackDump(L); 
        ///* true  10  true  nil  nil  */ 
    
        lua_settop(L, -5); 
        stackDump(L); 
        /* true  */ 
    
        lua_close(L);
        getchar();
        return 0;
    }

    这个vs不知怎搞的老是出现蛋疼的问题

  • 相关阅读:
    如何分配资源和管理资源
    让Project把周六和周日也计算工期
    Project设置子任务
    pytest-配置文件
    pytest-fixture
    pytest-标记
    pytest-断言
    pytest-参数化
    pytest入门
    maven-插件
  • 原文地址:https://www.cnblogs.com/zzyoucan/p/4322173.html
Copyright © 2011-2022 走看看