Lua學習筆記

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   io   檔案   

最近在學習Lua,腦子不好使,怕忘記了,所以記下來方便以後查閱:

首先,來瞭解幾個概念:

  lua_State  Lua解譯器

  lua_open  開啟一個lua解譯器,返回lua_State指標

  luaL_openlibs 載入預設lua庫

  luaL_dofile  解釋執行指令檔

  luaL_dostring  解釋執行指令碼字串

  lua_close 釋放lu解譯器

  //以上引用http://www.cnblogs.com/linbc/archive/2009/06/20/1507158.html

  一、c++調用lua

  編寫Lua代碼:

function test()    -- body    print("test:");    --return sub2(10,20);end

儲存為test.lua

編寫C++代碼:

#include "stdafx.h"extern "C"{#include "lua.h"#include "lualib.h"#include "lauxlib.h"}lua_State* L;int _tmain(int argc, _TCHAR* argv[]){    L = luaL_newstate();    luaL_openlibs(L);    luaL_dofile(L,"test.lua");    lua_getglobal(L, "test");    lua_pcall(L, 0, 0, 0);    lua_pop(L, 1);    lua_close(L);}

二、lua調用c++

lua代碼同樣是test.lua,開啟注釋--return sub2(10,20);

  c++代碼:

#include <stdio.h>#include <string.h>#include <lua.hpp>#include <lauxlib.h>#include <lualib.h>//待Lua調用的C註冊函數。static int add2(lua_State* L){    //檢查棧中的參數是否合法,1表示Lua調用時的第一個參數(從左至右),依此類推。    //如果Lua代碼在調用時傳遞的參數不為number,該函數將報錯並終止程式的執行。    double op1 = luaL_checknumber(L,1);    double op2 = luaL_checknumber(L,2);    //將函數的結果壓入棧中。如果有多個傳回值,可以在這裡多次壓入棧中。    lua_pushnumber(L,op1 + op2);    //傳回值用於提示該C函數的傳回值數量,即壓入棧中的傳回值數量。    return 1;}//另一個待Lua調用的C註冊函數。static int sub2(lua_State* L){    double op1 = luaL_checknumber(L,1);    double op2 = luaL_checknumber(L,2);    lua_pushnumber(L,op1 - op2);    return 1;}const char* testfunc = "print(add2(1.0,2.0)) print(sub2(20.1,19))";int main(){    lua_State* L = luaL_newstate();    luaL_openlibs(L);    //將指定的函數註冊為Lua的全域函數變數,其中第一個字串參數為Lua代碼    //在調用C函數時使用的全域函數名,第二個參數為實際C函數的指標。    lua_register(L, "add2", add2);    lua_register(L, "sub2", sub2);    //在註冊完所有的C函數之後,即可在Lua的代碼塊中使用這些已經註冊的C函數了。    if (luaL_dostring(L,testfunc))        printf("Failed to invoke.\n");    lua_close(L);    return 0;}

以上來自:http://www.cnblogs.com/stephen-liu74/archive/2012/07/23/2469902.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.