在LUA庫中添加自己的函數庫總結

來源:互聯網
上載者:User

1.首先下載基於VS的LUA源碼,地址為http://luabinaries.luaforge.net/download.html

2.在LIB工程中添加mylib.c檔案

3.在檔案當中添加如下的代碼

#include "lua.h"<br />#include "lauxlib.h"<br />#include "lualib.h"<br />static int myfun(lua_State* L)<br />{<br />printf("myfun is succeed!");<br />return 0;<br />}<br />static const struct luaL_Reg mylib[] =<br />{<br />{"myfun",myfun},<br />{NULL,NULL}<br />};<br />LUALIB_API int luaopen_mylib(lua_State* L)<br />{<br />luaL_register(L,"mylib",mylib);<br />}

4。在lualib.h中增加如下定義

#define LUA_MYLIBNAME"mylib"<br />LUALIB_API int (luaopen_mylib) (lua_State *L);

5.在linit.c,中將

 

static const luaL_Reg lualibs[] = {<br /> {"", luaopen_base},<br /> {LUA_LOADLIBNAME, luaopen_package},<br /> {LUA_TABLIBNAME, luaopen_table},<br /> {LUA_IOLIBNAME, luaopen_io},<br /> {LUA_OSLIBNAME, luaopen_os},<br /> {LUA_STRLIBNAME, luaopen_string},<br /> {LUA_MATHLIBNAME, luaopen_math},<br /> {LUA_DBLIBNAME, luaopen_debug},<br /> {LUA_MYLIBNAME,luaopen_mylib},<br /> {NULL, NULL}<br />};

最後增加一行,如所示

6.更新include目錄的lualib.h檔案

7.測試如下

#include "stdafx.h"<br />extern "C" {<br />#include "lua.h"<br />#include "lualib.h"<br />#include "lauxlib.h"<br />}<br />int main()<br />{<br />lua_State *L = luaL_newstate();<br />lua_cpcall(L, luaopen_base, 0);<br />lua_cpcall(L, luaopen_io, 0);<br />lua_cpcall(L, luaopen_string, 0);<br />lua_cpcall(L,luaopen_mylib,0);<br />const char *buf = "mylib.myfun()";//注意調用規則<br />//luaL_loadstring(L, buf);<br />int s = luaL_loadstring(L, buf);<br />if ( s==0 )<br />{<br />s = lua_pcall(L, 0, LUA_MULTRET, 0);<br />}<br />lua_close(L);<br />getchar();<br />return 0;<br />}<br />

ok

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.