目录结构

编译出来为我所需的文件,以及代码文件

├── bin
│   ├── test
│   └── test.lua
├── build
├── CMakeLists.txt
├── lua
│   ├── include
│   │   ├── lauxlib.h
│   │   ├── lua.h
│   │   ├── lua.hpp
│   │   ├── luaconf.h
│   │   └── lualib.h
│   └── lib
│       └── liblua.a
└── src
    └── main.cpp

源代码

//main.cpp
#include <stdio.h>

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

int main(int argc, char ** argv) {
    lua_State * L = luaL_newstate() ;        //创建lua运行环境
    if (!L) {
        printf("error for luaL_newstate\n");
    }
    luaopen_base(L);                         // 加载Lua基本库
    luaL_openlibs(L);                        // 加载Lua通用扩展库

    int ret = luaL_loadfile(L,"test.lua") ;  //加载lua脚本文件
    if (ret) {
        printf("error for luaL_loadfile\n");
    }
    ret = lua_pcall(L,0,0,0) ;
    if (ret) {
        printf("error for lua_pcall\n");
    }
    lua_getglobal(L,"printmsg");
    ret = lua_pcall(L,0,0,0);
    if (ret) {
        printf("error for lua_pcall\n");
    }

    return 0;
}
-- test.lua

function printmsg()
    print("hello word")
end
#CMakeLists.txt
PROJECT(test)
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)

set(EXECUTABLE_OUTPUT_PATH ../bin)

## libs
link_directories(/usr/local/lib)
link_directories(/usr/lib)

## includes
include_directories(/usr/local/include)
include_directories(./src SRC_DIR)
include_directories(./lua/include)

aux_source_directory(./src SRC_DIR)

## apps
add_executable(test
    ${SRC_DIR}
)

## link libs
target_link_libraries(test lua m dl)

编译运行

    $ cd build
    $ cmake ..
    $ make
    $ cd ../bin
    $ ./test
分享到 --

欢迎转载,转载请注明作者及出处oldblog.hanxi.info,请勿用于商业用途

本文地址:http://hanxi.github.io/2013/07/26/original-lua-hello-world