1. 程式人生 > >lua與c (一)Mac下c 和lua環境搭建

lua與c (一)Mac下c 和lua環境搭建

由於工作中一直用的是lua開發,可以把lua看作是膠水語言,和c有很好的親和性,最近想研究一下c與lua之間呼叫的原理。

1.lua的安裝

tar -xvf lua-5.3.2.tar.gz #解壓縮
cd lua-5.3.2
sudo make maxos test
sudo make install

然後輸入lua, 出現下面內容說明lua安裝成功

Lua 5.3.2 Copyright (C) 1994-2015 Lua.org, PUC-Rio

2.xcode中新建專案

在xcode中新建一個c專案,然後右鍵匯入lua.h,lualib.h,lauxlib.h,luaconf.h,liblua.a( 這幾個檔案都可以在上一步下載的原始碼中找到)。
這裡寫圖片描述

3.程式碼例項

//
//  main.c
//  CLua
//
//  Created by cheng on 16/1/6.
//  Copyright (c) 2016年 cheng. All rights reserved.
//

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


int main(int argc, const char * argv[]) {
    // insert code here...
    lua_State *L = luaL_newstate();  /* opens Lua */
luaL_openlibs(L); /* opens the standard libraries */ luaL_dofile(L,"/Users/cheng/Documents/CLua/lua/test.lua"); /* runs Lua script */ lua_close(L); return 0; }
function saysth()
    print("hello world");
end
myname = "loster";
saysth();

執行結果:
這裡寫圖片描述