c语言调用lua

1.首先要下载安装lua环境
安装

进入官方站点(http://www.lua.org/download.html )下载最新的安装包。当前是 Lua 5.2.0

wget -c http://www.lua.org/ftp/lua-5.2.0.tar.gz

解压:

tar zxvf lua-5.2.0.tar.gz

安装readline

wget -c ftp://ftp.gnu.org/gnu/readline/readline-6.2.tar.gz

tar -zxvf readline-6.2.tar.gz

cd readline-6.2

./configure //这个地方一定要指定路径,要不然要报错(一般在/usr/local下用软件命名,比如 /usr/local/readline下)

make && make installl

或:

yum -y install readline-devel ncurses-devel

进入解压的目录:

cd lua-5.2.0

make linux

make install

直接在命令行输入:lua 如果进入编辑模式,表示安装成功。

在编辑模式中输入:

print(‘Hi,this is my first lua program!’)

回车
2.代码示例

#include <lua.h>
#include <lauxlib.h>

#include <stdlib.h> /* For function exit() */
#include <stdio.h> /* For input/output */

void lua_print(lua_State *L, double x) { /* call lua print */
    /* push functions and arguments */
    lua_getglobal(L, "print"); /* function to be called */
    lua_pushnumber(L, x); /* push 1st argument */
    /* do the call (1 arguments, 1 result) */
    if (lua_pcall(L, 1, 0, 0) != 0)
    {
        return;
    }
    return;
}
int main(int argc, const char *argv[])
{
    lua_State *L = luaL_newstate(); /* Create new lua state variable */
    /* Load Lua libraries, otherwise, the lua function in *.lua will be nil */
    luaL_openlibs(L);
    lua_print(L,1);
    lua_close(L);                   /* Close the lua state variable */

    return 0;
}

gcc -o test main.c -llua
运行结果:1

3.调用lua脚本

如type.lua 内容

print(type("hello world"))
print(type(19.4))
print(type(print))
print(type(true))
print(type(nil))
print(type(type(X)))

type.c 文件调用示例:

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

void main()
{
    int retCode;
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    retCode = luaL_dofile(L,"type.lua");
    if (retCode != 0)
    {
        printf("error %s\n",lua_tostring(L,-1));
        return;
    }

    lua_close(L);
}

gcc -o type type.c -llua
运行结果:
string
number
function
boolean
nil
string

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值