#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#pragma mark - Lua调用C语言代码
int sayHello(lua_State *L) {
printf(
"无参C方法\n");
return 0;
}
int getStringFun(lua_State *L) {
const char * name = luaL_checkstring(L,
1);
char buff[
100];
memset(buff,
0,
100);
sprintf(buff,
"Hello %s\n",name);
lua_pushstring(L, buff);
printf(
"有参C方法%s\n",lua_tostring(L, -
1));
lua_pop(L,
1);
return 1;
}
#pragma mark - 访问Lua中的全局变量
void callglobelGaram(lua_State *L){
printf(
"\n");
printf(
"访问Lua中的全局变量: \n");
lua_getglobal(L,
"name");
lua_getglobal(L,
"version");
printf(
"version:%s\n",lua_tostring(L, -
1));
lua_pop(L,
1);
printf(
"name:%s\n",lua_tostring(L, -
1));
lua_pop(L,
1);
printf(
"\n");
printf(
"访问Lua中的全局变量table的值: \n");
lua_getglobal(L,
"people");
lua_getfield(L,
1,
"name");
if (lua_isstring(L, -
1)) {
printf(
"people.name:%s\n",lua_tostring(L, -
1));
lua_pop(L,
1);
}
lua_getfield(L,
1,
"age");
if (lua_isstring(L, -
1)) {
printf(
"people.age:%s\n",lua_tostring(L, -
1));
lua_pop(L,
1);
}
lua_getfield(L,
1,
"sex");
if (lua_isstring(L, -
1)) {
printf(
"people.sex:%s\n",lua_tostring(L, -
1));
lua_pop(L,
1);
}
lua_pop(L,
1);
}
#pragma mark - C调用Lua方法
void callLua_Func(lua_State *L){
printf(
"\n");
printf(
"C调用Lua方法: \n");
lua_getglobal(L,
"main");
lua_call(L,
0,
0);
lua_getglobal(L,
"getString");
lua_pushstring(L,
"ZhangSan");
lua_call(L,
1,
1);
if (lua_isstring(L, -
1)) {
printf(
"%s\n",lua_tostring(L, -
1));
}
lua_pop(L,
1);
}
#pragma mark - Lua调用C方法
void callC_Fun(lua_State *L){
printf(
"\n");
printf(
"Lua调用C方法: \n");
lua_register(L,
"sayHello", sayHello);
lua_register(L,
"getStringFun", getStringFun);
}
int main(
int argc,
const char * argv[]) {
@autoreleasepool {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
char *str =
"hello.lua";
callC_Fun(L);
luaL_dofile(L, str);
callLua_Func(L);
callglobelGaram(L);
lua_close(L);
}
return 0;
}
--全局变量
version =
2.1;
name =
"eoe";
--table型数据
people = {
name =
"zhangsan",
age =
20,
sex =
"男"
}
--Lua(无参)方法
function main()
print(
"hello fun");
end
--Lua(有参)方法
function getString(name)
return "hello "..name;
end
--Lua调用C(无参)方法
sayHello();
--Lua调用C(有参)方法
getStringFun(
"abc");