自己写一个lua.exe

2018-02-05  本文已影响292人  ManjackGo
#include "stdafx.h"

#include <iostream>
#include <string>

using namespace std;

extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}

int _tmain(int argc, _TCHAR* argv[])
{
    lua_State *L = luaL_newstate();
    luaopen_base(L);
    if (L == NULL) {
        return 0;
    }

    char lua_code_buff[50];
    int error;

    string tip = "Please Enter Your Lua Code\n";
    cout << tip;
    while (cin.getline(lua_code_buff, 50)){
        error = luaL_loadbuffer(L, lua_code_buff, strlen(lua_code_buff), "line")
            || lua_pcall(L, 0, 0, 0);
        if (error){
            cout << string("LUA ERROR:") + lua_tostring(L, -1) << endl;
            lua_pop(L, 1);
        }
        else {
            //auto ret = lua_tonumber(L, -1);
            //cout << ret << endl;
        }
    }

    lua_close(L);
    system("pause");
    return 0;
}
}

在lua5.1及之后,五句luaopen只需换成一句luaL_openlibs
使用已编译的lua.exe的用法,我们平时都是配置环境变量,然后打一句lua,然后输入你的lua代码来执行。这个lua.exe简单来说就可以概括为以上的代码。

上一篇 下一篇

猜你喜欢

热点阅读