在IOS项目中使用Lua

1.Lua是一个用C语言编写的解析器,用来解析执行lua代码的,因此便可以把它用户任何支持C语言的平台、编译环境或者项目,http://www.lua.org/download.html

2。 在官网中下载lua的开源代码,解压出来目录如下:
      屏幕快照-2014-09-19-下午3.33.30.png
      其中源码都在src目录下,里面主要是.h 和.c的文件  还有一个makefile文件(编译生成不同平台的库),在这里就不使用makefile预先生成.a的库了,直接整个src目录拉入工程编译,其中要将lua.c 、luac.c去掉,否则会出编译错误,重复的符号定义,不知道为什么,去掉就是,那个makefile文件也不要添加到工程里了吧
 
Lua的本质是C,不是C++,Lua提供给C用的API也都是基于面向过程的C函数来用的

3. 在ViewController文件下编码如下:
    #import "ViewController.h"

#ifdef __cplusplus //这个宏只有在C++环境中定义,表示如果是在C++环境下,则把下面include这几个头文件的内容编译生成的内部符号名使用C约定
extern "C"
{
#endif
   
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
   
#ifdef __cplusplus
}
#endif

//要想注册进lua,函数的定义为 typedef int (*lua_CFunction)(lua_State* L)
int printHello(lua_State * l)
{
    lua_pushstring(l,"hello lua");
   
    //返回值代表向栈内压入的元素个数
    return 1;
}

int foo(lua_State * l)
{
    //获得Lua传递过来的参数个数
    int n = lua_gettop(l);
    if(n != 0)
    {
        //获得第一个参数
        int i = lua_tonumber(l,1);
        //将传递过来的参数加一以后最为返回值传递回去
        lua_pushnumber(l,i+1);
        return 1;
    }
   
    return 0;
}

//相加
int add(lua_State * l)
{
    int n = lua_gettop(l);
    int sum = 0;
    for (int i=0;i
    {
        sum += lua_tonumber(l,i+1);
    }
    if(n!=0)
    {
        lua_pushnumber(l,sum);
        return 1;
    }
   
    return 0;
}

//把需要用到的函数都放到注册表中,统一进行注册
const luaL_Reg lib[]=
{
    {"printHello",printHello},
    {"foo",foo},
    {"add",add},
    {nullptr,nullptr}
};


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
    //创建一个新的Lua环境
    lua_State * l= luaL_newstate();
   
    //打开需要的库
    luaL_openlibs(l);
   
    //把foo函数注册进lua,第二个参数代表Lua中要调用的函数名称,第三个参数就是c层的函数名称
    //单独注册一个函数
    //    lua_register(l,"foo",foo);
   
    //统一注册lua中调用的函数
    const luaL_Reg* libf =lib;
    for (; libf->func; libf++)
    {
        //把foo函数注册进lua,第二个参数代表Lua中要调用的函数名称,第三个参数就是c层的函数名称
        lua_register(l,libf->name,libf->func);
        //将栈顶清空
        lua_settop(l,0);
    }
   
    //加载并且执行lua文件
    NSString *plistFilePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"lua"];
    int i = luaL_dofile(l,[plistFilePath cStringUsingEncoding:NSUTF8StringEncoding]);
    //使用dostring直接执行字符串代表的内容,是一段Lua代码
    //    luaL_dostring(l,"print(foo(100))");
    if (1 == i) {
        const char* error;
        error = lua_tostring(l, -1);//打印错误结果
        printf("%s",error);
        lua_pop(l, 1);
    }
   
    //关闭
    lua_close(l);
   
   
}
原文地址:https://www.cnblogs.com/cnsec/p/11515777.html