歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Lua 中棧操作的C API示例

Lua 中棧操作的C API示例

日期:2017/3/1 9:39:46   编辑:Linux編程

這是《Lua程序設計》中的例子,做個簡單記錄。

Lua程序設計(第2版)中文 PDF http://www.linuxidc.com/Linux/2013-03/81833.htm

#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;
}

運行結果:

簡單畫個示意圖:

Lua 語言 15 分鐘快速入門 http://www.linuxidc.com/Linux/2013-06/86582.htm

Lua程序設計(第二版)閱讀筆記 http://www.linuxidc.com/Linux/2013-03/81834.htm

NetBSD 將支持用 Lua 腳本開發內核組件 http://www.linuxidc.com/Linux/2013-02/79527.htm

CentOS 編譯安裝 Lua LuaSocket http://www.linuxidc.com/Linux/2011-08/41105.htm

Lua 的詳細介紹:請點這裡
Lua 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved