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 
#include 

#include  /* For function exit() */
#include  /* 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 
#include 
#include 
#include 

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

你可能感兴趣的:(lua,lua)