Luaスタックへ値をプッシュする場合,lua_push***関数を呼び出します. ***の部分にはデータ型が入ります. 例えばboolean型をプッシュする場合はbooleanが,number型をプッシュする場合はnumberが入ります.
lua_pushboolean(L, 1);
lua_pushnumber(L, 10.5);
lua_pushinteger(L, 3);
lua_pushstring(L, "Hello world");
lua_pushnil(L);
Lua関係の関数は殆どの場合,第1引数にlua_Stateを渡す必要があります.
#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
void dumpStack(lua_State* L)
{
int i;
//スタックに積まれている数を取得する
int stackSize = lua_gettop(L);
for( i = stackSize; i >= 1; i-- ) {
int type = lua_type(L, i);
printf("Stack[%2d-%10s] : ", i, lua_typename(L,type) );
switch( type ) {
case LUA_TNUMBER:
//number型
printf("%f", lua_tonumber(L, i) );
break;
case LUA_TBOOLEAN:
//boolean型
if( lua_toboolean(L, i) ) {
printf("true");
}else{
printf("false");
}
break;
case LUA_TSTRING:
//string型
printf("%s", lua_tostring(L, i) );
break;
case LUA_TNIL:
//nil
break;
default:
//その他の型
printf("%s", lua_typename(L, type));
break;
}
printf("\n");
}
printf("\n");
}
int main (void)
{
lua_State* L = luaL_newstate();
lua_pushboolean(L, 1); //trueをpush
dumpStack(L);
lua_pushnumber(L, 10.5); //10.5をpush
dumpStack(L);
lua_pushinteger(L, 3); //3をpush
dumpStack(L);
lua_pushnil(L); //nilをpush
dumpStack(L);
lua_pushstring(L, "Hello world"); //hello worldをpush
dumpStack(L);
lua_close(L);
return 0;
}
ここではLuaスタックの状態を見るためdumpStack関数を作成しました. この関数内の処理は現段階では理解しなくて結構です.
スタックの一番下は1番目となっています. 値をプッシュするごとに2番目,3番目と積み重ねられていきます. dumpStack関数はスタックの位置,スタックに格納されているデータ型,及び データの中身を表示します. ただし,データの中身を表示できるのは,number,boolean,string,nilに限ります.
実行結果
Stack[ 1- boolean] : true
Stack[ 2- number] : 10.500000
Stack[ 1- boolean] : true
Stack[ 3- number] : 3.000000
Stack[ 2- number] : 10.500000
Stack[ 1- boolean] : true
Stack[ 4- nil] :
Stack[ 3- number] : 3.000000
Stack[ 2- number] : 10.500000
Stack[ 1- boolean] : true
Stack[ 5- string] : Hello world
Stack[ 4- nil] :
Stack[ 3- number] : 3.000000
Stack[ 2- number] : 10.500000
Stack[ 1- boolean] : true