LUAスクリプトはCシーンを呼び出し、C APIを使用してスクリプト構造のテーブルにアクセスする

4553 ワード

LUA呼び出しC
lua解析にはいくつかのシステムサービスが統合されているため、スクリプトではシステムリソースにアクセスできます.たとえば、luaスクリプトはファイルシステムインタフェースを呼び出し、数学ライブラリを呼び出すことができます.
しかし、luaスクリプトではアクセスできないシステムサービスや拡張機能が常に存在し、これらのシステムサービスや拡張機能がC言語で実現されている場合、
では、luaライブラリのCライブラリのカプセル化方法を使用して、その機能をluaインタフェースにカプセル化し、スクリプトがこれらのluaインタフェースを呼び出してこれらの機能を呼び出すことができます.
-------
この場合,luaスクリプトをホストプログラムとする.
 
C LUAを呼び出す
もう1つのシナリオは、CプログラムがホストプログラムとしてLUAスクリプトを呼び出し、例えばluaスクリプトをプロファイル機能とし、
C言語はCapiを呼び出してluaスクリプトを実行し,その構成値を取得する.
 
この例では、第1のケースと結びつけて、Cでluaスクリプトのテーブルパラメータを取得する方法について説明します.
 
LUA C API
lua c apiの紹介:http://www.cnblogs.com/stephen-liu74/archive/2012/07/18/2433428.html
主にgetfieldインタフェースを使用して、テーブル内のkeyの値にアクセスします.lua_getfield
[-0, +1, e]
void lua_getfield (lua_State *L, int index, const char *k);

Pushes onto the stack the value t[k] , where t is the value at the given valid index. As in Lua, this function may trigger a metamethod for the "index"event (see §2.8).
表を巡回する方法:
http://blog.csdn.net/chencong112/article/details/6908041
http://www.cnblogs.com/chuanwei-zhang/p/4077247.html

lua_getglobal(L, t);
lua_pushnil(L);
while (lua_next(L, -2)) {
    /*      -1    value, -2    key */
    lua_pop(L, 1);
}

 
lua_getglobal(L, t);
len = lua_objlen(L, -1);
for (i = 1; i <= len; i++) {
    lua_pushinteger(L, i);
    lua_gettable(L, -2);
    /*        t[i]    */
    lua_pop(L, 1);
}

 
DEMO
説明:cを使用してluaインタフェースをカプセル化し、このインタフェースはテーブルに転送され、Cでこのテーブルのkey値にアクセスします.
 
-- temperature conversion table (celsius to farenheit)
require "test"

test.printTable({["a"]="aa"})

 
 

#include <stdlib.h>
#include <math.h>

#define lmathlib_c
#define LUA_LIB

#include "lua.h"

#include "lauxlib.h"
#include "lualib.h"



static int printTable (lua_State *L) {
  printf("%s
", "hello world"); int n = lua_gettop(L); if ( n != 1 ) { printf("%s
", "printTable must has one arg"); } if ( lua_istable(L, -1) ) { lua_getfield(L, -1, "a"); printf("arg one table[a]=%s
", lua_tostring (L, -1)); } else { printf("%s
", "printTable arg must be table"); } return 0; } static const luaL_Reg testlib[] = { {"printTable", printTable}, {NULL, NULL} }; LUALIB_API int luaopen_test (lua_State *L) { luaL_register(L, "test", testlib); return 1; }

印刷:
:~/share_windows/openSource/lua/lua-5.1.5$ lua ./test/test.lua hello worldarg one table[a]=aa