2012-11-18 2 views
5

Lua은 무료 온라인 (버전 5.2 (0120) 용 reference manual)과 함께 Programming in Lua (5.0 버전)도 제공됩니다.루아 5.2 임베딩 및 라이브러리 정의

그러나 이러한 버전간에 몇 가지 변화가 있었지만 나는 능가 할 수없는 것처럼 보였습니다. 변경 사항은 5.25.1에 대한 참조 설명서의 연속 버전에 나와 있습니다. luaL_openlib()의 연속 사용 중단은 luaL_register()이고, 그 다음은 luaL_register()이고, 보조는 luaL_setfuncs()입니다.

웹상에서 검색 한 결과가 많아서 대부분은 luaL_register()입니다. 예상 t1()를 입력하면 예상 된 결과를 생산으로이 작동 내가 그 컴파일과 말과 연결될 수 아래의 미니 프로그램으로 요약 할 수있다 달성하려고 gcc ./main.c -llua -ldl -lm -o lua_test

#include <lua.h> 
#include <lauxlib.h> 
#include <lualib.h> 

#include <stdio.h> 
#include <string.h> 


static int test_fun_1(lua_State * L) 
{ 
    printf("t1 function fired\n"); 
    return 0; 
} 

int main (void) 
{ 
    char buff[256]; 
    lua_State * L; 
    int error; 

    printf("Test starts.\n\n"); 

    L = luaL_newstate(); 
    luaL_openlibs(L); 

    lua_register(L, "t1", test_fun_1); 

    while (fgets(buff, sizeof(buff), stdin) != NULL) 
    { 
     if (strcmp(buff, "q\n") == 0) 
     { 
      break; 
     } 
     error = luaL_loadbuffer(L, buff, strlen(buff), "line") || 
       lua_pcall(L, 0, 0, 0); 
     if (error) 
     { 
     printf("Test error: %s\n", lua_tostring(L, -1)); 
     lua_pop(L, 1); 
     } 
    } 
    lua_close(L); 

    printf("\n\nTest ended.\n"); 
    return 0; 
} 

.

이제 루아가 볼 수있는 라이브러리/패키지를 만들고 싶습니다. Programming in Lua 조언 우리 to use 배열 및로드 기능 :

static int test_fun_2(lua_State * L) 
{ 
    printf("t2 function fired\n"); 
    return 0; 
} 

static const struct luaL_Reg tlib_funcs [] = 
{ 
    { "t2", test_fun_2 }, 
    { NULL, NULL } /* sentinel */ 
}; 

int luaopen_tlib (lua_State * L) 
{ 
    luaL_openlib(L, "tlib", tlib_funcs, 0); 

    return 1; 
} 

다음 luaL_openlibs()luaopen_tlib()를 사용합니다. 이렇게하면 LUA_COMPAT_MODULE (호환 모드에서 작동)을 정의하면 tlib:t2()을 사용할 수 있습니다.

루아 5.2에서 이것을하는 적절한 방법은 무엇입니까?

int luaopen_tlib (lua_State * L) 
{ 
    luaL_newlib(L, tlib_funcs); 
    return 1; 
} 

그리고 main 기능에

, 당신은 다음과 같은 모듈을로드해야합니다 :

답변

8

luaopen_tlib 기능은 그런 식으로 작성해야

int main (void) 
{ 
    // ... 
    luaL_requiref(L, "tlib", luaopen_tlib, 1); 
    // ... 
} 

또는 양자 택일로, 당신이 항목을 추가 할 수 있습니다 {"tlib", luaopen_tlib}loadedlibs 테이블의 linit.c.

+0

luaL_openlibs는 선택 사항이며 예를 들어있을 수 없습니다. – Cubic

+0

중요한 줄만 표시되도록 예제를 편집했습니다. – prapin