관리 메뉴

Value Creator의 IT(프로그래밍 / 전자제품)

#4. [LUA] C 또는 C++ 과 Lua script연동 본문

1. 프로그래밍/2) LUA

#4. [LUA] C 또는 C++ 과 Lua script연동

valuecreatort 2019. 4. 18. 19:59
반응형

0. 전문

아래의 3가지 정보 모두 알고 있어야 원활하게 수행 가능하다.

하지만 정보가 흩어져 있어서 어렵다.

따라하기만 하면 되도록 순서를 잘 정리하였다.

 

...더보기

1) 아래 첨부파일이 제일 잘 정리되어 있으나 include, library 넣는 방법이 빠져있다.

c_lua_script.pdf
0.63MB

...더보기

2) Lua 스크립트를 C언어에서 불러오는 소스코드

http://lua-users.org/wiki/SimpleLuaApiExample

 

lua-users wiki: Simple Lua Api Example

This is a simple introductory example of how to interface to Lua from C. The C program loads a Lua script file, sets some Lua variables, runs the Lua script, and reads back the return value. The below example works with Lua 5.3. First, create the below Lua

lua-users.org

 

Visual Studio에 외부 라이브러리 추가하기

Visual Studio에서 외부 라이브러리를 연결하는 법을 스크린샷으로 하나씩 설명해 놓았습니다.

blessingdev.wordpress.com

1. 개요

기초 지식 없이 lua와 C를 연동할 수 있도록 함. 아래 글대로 따라하기만 하면 연동가능.

 

2. 가정

LuaForWindows가 깔려 있다고 가정한다. 안 깔려있다면 아래 글 참조

2019/04/19 - [분류 전체보기] - #5. [LUA] Lua 설치하기(Lua For Windows)

 

Lua 편집 툴은 Eclipse 기반의 Lua Development Tools를 활용

2019/03/19 - [1. 프로그래밍/1) UML, LUA, QT] - #1 Lua 프로그래밍 Chap 0. Lua Development Tools 활용(특징 : Eclipse 기반, 자동 완성기능)

 

3. 순서

1. Lua Development Tools 에서 'script.lua' 라는 파일을 만든다.

[소스코드]

-- script.lua
-- Receives a table, returns the sum of its components.
io.write("The table the script received has:\n");
x = 0
for i = 1, #foo do
print(i, foo[i])
x = x + foo[i]
end
io.write("Returning data back to C\n");
return x

 

2. Visual studio를 연다(Visual studio 2012 기준).

새 프로젝트를 만든다(C++ Win 32 Console 기준).

test4라는 프로젝트를 만들었다.

빈 프로젝트로 만들었다.

 

 

 

3. C언어에서 Lua 호출하는 예제를 만든다.

소스 파일에 'test5.c'라는 파일을 만든다.

 

 

아래의 소스코드를 넣는다.

[소스코드]

/*
* test.c
* Example of a C program that interfaces with Lua.
* Based on Lua 5.0 code by Pedro Martelletto in November, 2003.
* Updated to Lua 5.1. David Manura, January 2007.
*/

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


int
main(void)
{
int status, result, i;
double sum;
lua_State *L;

/*
* All Lua contexts are held in this structure. We work with it almost
* all the time.
*/
L = luaL_newstate();

luaL_openlibs(L); /* Load Lua libraries */

/* Load the file containing the script we are going to run */
status = luaL_loadfile(L, "script.lua");
if (status) {
/* If something went wrong, error message is at the top of */
/* the stack */
fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1));
exit(1);
}

/*
* Ok, now here we go: We pass data to the lua script on the stack.
* That is, we first have to prepare Lua's virtual stack the way we
* want the script to receive it, then ask Lua to run it.
*/
lua_newtable(L); /* We will pass a table */

/*
* To put values into the table, we first push the index, then the
* value, and then call lua_rawset() with the index of the table in the
* stack. Let's see why it's -3: In Lua, the value -1 always refers to
* the top of the stack. When you create the table with lua_newtable(),
* the table gets pushed into the top of the stack. When you push the
* index and then the cell value, the stack looks like:
*
* <- [stack bottom] -- table, index, value [top]
*
* So the -1 will refer to the cell value, thus -3 is used to refer to
* the table itself. Note that lua_rawset() pops the two last elements
* of the stack, so that after it has been called, the table is at the
* top of the stack.
*/
for (i = 1; i <= 5; i++) {
lua_pushnumber(L, i); /* Push the table index */
lua_pushnumber(L, i*2); /* Push the cell value */
lua_rawset(L, -3); /* Stores the pair in the table */
}

/* By what name is the script going to reference our table? */
lua_setglobal(L, "foo");

/* Ask Lua to run our little script */
result = lua_pcall(L, 0, LUA_MULTRET, 0);
if (result) {
fprintf(stderr, "Failed to run script: %s\n", lua_tostring(L, -1));
exit(1);
}

/* Get the returned value at the top of the stack (index -1) */
sum = lua_tonumber(L, -1);

printf("Script returned: %.0f\n", sum);

lua_pop(L, 1); /* Take the returned value out of the stack */
lua_close(L); /* Cya, Lua */

return 0;
}

 

 

 

4. Lua 헤더 파일을 include 한다. 경로는 아래 그림 참고.

 

 

 

 

 

 

 

 

 

 

5. Lua 라이브러리를 링크한다. 추가 라이브러리 디렉터리에 넣는다. 경로는 아래 그림 참고.

 

 

6. Lua 라이브러리를 추가 종속성에 넣는다.

 

 

 

 

7. 아래 그림같이 lua.h, lualib.h, lauxlib.h에 빨간줄이 모두 없어졌다.

정상적으로 헤더파일과 라이브러리가 링크 되었음을 알 수 있다.

 

8. lua5.1.dll과 lua51.dll, script.lua를 프로젝트 폴더에 집어넣는다.

dll파일은 C:\Program Files (x86)\Lua\5.1\lib경로에 있을 것이다.

script.lua 파일은 맨 처음 작성한 워크스페이스에 있을 것이다.

아래 그림과 같이 넣는다.

 

 

9. C 프로젝트를 빌드 한다.(단축키 F7)

 

10. C 프로젝트를 실행시키면, 정상 동작하는 것을 볼 수 있다.(단축키 컨트롤 F5)

 

 

 

 

 

4. 참고자료

 

 

 

반응형
Comments