lua学习例子

extern "C"{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib,"lua.lib") 
void error(lua_State* L, const char* fmt, ...)
{
    va_list argp;
    va_start(argp, fmt);
    vfprintf(stderr, fmt, argp);
    va_end(argp);
    lua_close(L);
    exit(EXIT_FAILURE);
}

void load(char* filename, int* width, int* height)
{
    lua_State* L = luaL_newstate();
    luaopen_base(L);
    luaopen_io(L);
    luaopen_string(L);
    luaopen_math(L);

    if (luaL_loadfile(L, filename) || lua_pcall(L, 0, 0, 0))
        error(L, "cannot run configuration file:%s", lua_tostring(L, -1));
    lua_getglobal(L, "width");//每次调用将相应变量压入栈顶
    lua_getglobal(L, "height");
    if (!lua_isnumber(L, -2))//lua_isnumber函数判断每个值是否为数字
        error(L, "width should be a number");
    if (!lua_isnumber(L, -1))
        error(L, "height should be a number");
    *width = (int)lua_tonumber(L, -2);//lua_tonumber函数将得到的数值转换成double类型并用(int)强制转换成整型
    *height = (int)lua_tonumber(L, -1);

    lua_close(L);
}

int main()
{
    int width = 0;
    int height = 0;
    load("pp.lua", &width, &height);
    return 0;
}
原文地址:https://www.cnblogs.com/zzyoucan/p/5933470.html