c 使用lua 示例

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

static int say_hello(lua_State *L)
{
    const char *s = lua_tostring(L,1);
    printf("hell,%s\n",s);
    return 0;
}

int main(void)
{
    lua_State *L = luaL_newstate();;
    luaL_openlibs(L);
    
    //写入全局变量

    lua_pushnumber( L, 211 );
    lua_setglobal( L, "hp" );

    //lua_pop(L,2);

    //读取全局变量
    lua_getglobal( L, "hp" );   
    int res = lua_tointeger(L, -1);
        printf("%d\n",res);

    lua_pop(L,1);

    //设置一个有名称的table
    lua_newtable(L);

    lua_pushinteger(L, 10025);
    lua_setfield(L, 1, "id");

    lua_pushinteger(L, 3);
    lua_setfield(L, 1, "good_count");

    lua_pushinteger(L, 100);
    lua_setfield(L, 1, "count");

    lua_pushinteger(L, 15);
    lua_setfield(L, 1, "outlet_count");

    lua_setglobal(L,"customer_table");
        
    //读取table中的值
    int result;
    lua_getglobal(L,"customer_table");
    lua_pushstring(L,"count");
    lua_gettable(L,-2);
    result = lua_tointeger(L,-1);
    printf("%d\n",result);
    lua_pop(L,1);
    
    lua_pushstring(L,"outlet_count");
    lua_gettable(L,-2);
    result = lua_tointeger(L,-1);
    printf("%d\n",result);
    lua_pop(L,1);

    //函数相互调用    

    lua_register(L,"say_hello",say_hello);


    const char* dosomething = " \
        function dosomething(words)\
            say_hello(words) \
        end \
    ";

    luaL_dostring(L,dosomething);
     lua_getglobal(L, "dosomething");
    lua_pushstring(L,"yexuqiang");
        res = lua_pcall(L, 1, 1,0);
    printf("res:%d\n",res);

    
    lua_close(L);   
    return 0;
}

转载于:https://www.cnblogs.com/qianlicao/p/10794984.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值