일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 편편집 #강남역맛집 #강남샤브샤브 #강남무한리필 #편백찜맛집 #월남쌈맛집 #샤브샤브맛집 #가성비맛집 #강남회식 #강남데이트
- QTcpServer
- 순남시래기 #교대맛집 #교대역맛집 #한식맛집 #시래기국 #서울맛집 #가성비맛집 #건강한식단 #셀프반찬 #직장인맛집
- lua interpreter
- #서초구맛집 #교대역된장찌개 #옥된장교대점 #서초된장맛집 #교대직장인맛집 #된장찌개전문점 #서울된장정식 #혼밥맛집 #건강한한끼 #교대점심맛집
- file read
- 전동포 #송파구전기자전거 #전동킥보드수리 #모토벨로대리점 #전기자전거판매 #전동스쿠터수리 #배터리수리 #전기자전거수리 #송파구전동킥보드 #전동이동수단
- 찾다죽는줄
- #신혼부부 #결혼준비 #신혼부부희망타운신혼부부특별공급
- lua for windows
- QT TCP
- C++ API
- 육전국밥 #강남역맛집 #24시간맛집 #소고기국밥 #육전 #모둠전 #해물파전 #강남한식 #혼밥맛집 #강남역국밥
- 중소규모택지
- lua setup
- Lua
- 티몬삼겹살데이
- 수도권주택공급
- #부동산전자거래 #부동산전자계약 #부동산계약 #부동산전자계약방법 #부동산전자계약하는법 #부동산계약방법 #부동산중개수수료 #부동산중개수수료아끼기 #부동산복비아끼기
- 엑스퍼트생일축하해
- file write
- 등록임대주택
- TCP/IP
- 엑스퍼트2주년
- FILE TRANSFER
- 월세
- 국토교통부
- lua install
- object
- C API
- Today
- Total
Value Creator의 IT(프로그래밍 / 전자제품)
#4. [LUA] C 또는 C++ 과 Lua script연동 본문
0. 전문
아래의 3가지 정보 모두 알고 있어야 원활하게 수행 가능하다.
하지만 정보가 흩어져 있어서 어렵다.
따라하기만 하면 되도록 순서를 잘 정리하였다.
1) 아래 첨부파일이 제일 잘 정리되어 있으나 include, library 넣는 방법이 빠져있다.
2) Lua 스크립트를 C언어에서 불러오는 소스코드
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를 활용
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. 참고자료
'1. 프로그래밍 > 2) LUA' 카테고리의 다른 글
#6 [lua 1.1] 개요 - Lua 내부 코드 읽어보기 (0) | 2019.08.21 |
---|---|
#5. [LUA] Lua 설치하기(Lua For Windows) (0) | 2019.04.19 |
#3 Lua Tutorial ( File 열기, 쓰기 / 파일호출 / table 및 metatable) (0) | 2019.04.17 |
#2 Lua 모든 문법 핵심 요약 (0) | 2019.04.12 |
#1 Lua 프로그래밍 Chap 0. Lua Development Tools 활용(특징 : Eclipse 기반, 자동 완성기능) (0) | 2019.03.19 |