반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- 찾다죽는줄
- lua interpreter
- 월세
- QTcpServer
- 육전국밥 #강남역맛집 #24시간맛집 #소고기국밥 #육전 #모둠전 #해물파전 #강남한식 #혼밥맛집 #강남역국밥
- object
- file write
- 수도권주택공급
- 순남시래기 #교대맛집 #교대역맛집 #한식맛집 #시래기국 #서울맛집 #가성비맛집 #건강한식단 #셀프반찬 #직장인맛집
- lua for windows
- 전동포 #송파구전기자전거 #전동킥보드수리 #모토벨로대리점 #전기자전거판매 #전동스쿠터수리 #배터리수리 #전기자전거수리 #송파구전동킥보드 #전동이동수단
- 편편집 #강남역맛집 #강남샤브샤브 #강남무한리필 #편백찜맛집 #월남쌈맛집 #샤브샤브맛집 #가성비맛집 #강남회식 #강남데이트
- 엑스퍼트2주년
- 등록임대주택
- TCP/IP
- lua setup
- lua install
- 국토교통부
- C API
- 중소규모택지
- FILE TRANSFER
- #부동산전자거래 #부동산전자계약 #부동산계약 #부동산전자계약방법 #부동산전자계약하는법 #부동산계약방법 #부동산중개수수료 #부동산중개수수료아끼기 #부동산복비아끼기
- #신혼부부 #결혼준비 #신혼부부희망타운신혼부부특별공급
- C++ API
- 엑스퍼트생일축하해
- Lua
- file read
- QT TCP
- 티몬삼겹살데이
- meta table
Archives
- Today
- Total
Value Creator의 IT(프로그래밍 / 전자제품)
#12 [lua 1.1] table.h, table.c 파일 읽기 본문
반응형
table.h
Table.h에 익스턴 변수 이름을 보니 심볼 테이블을 구현한 것 같습니다.
/*
** Module to control static tables
** TeCGraf - PUC-Rio
** $Id: table.h,v 2.1 1994/04/20 22:07:57 celes Exp $
*/
#ifndef table_h
#define table_h
//심볼 테이블
extern Symbol *lua_table;
extern Word lua_ntable;
//상수 테이블
extern char **lua_constant;
extern Word lua_nconstant;
//문자열 테이블
extern char **lua_string;
extern Word lua_nstring;
//배열 테이블
extern Hash **lua_array;
extern Word lua_narray;
extern char *lua_file[];
extern int lua_nfile;
extern Word lua_block;
extern Word lua_nentity;
int lua_findsymbol (char *s);
int lua_findconstant (char *s);
void lua_travsymbol (void (*fn)(Object *));
void lua_markobject (Object *o);
void lua_pack (void);
void lua_stringcollector (void);
char *lua_createstring (char *s);
int lua_addfile (char *fn);
int lua_delfile (void);
char *lua_filename (void);
void lua_nextvar (void);
#endif
위에서부터 순서대로 심볼 테이블, 상수 테이블, 문자열 테이블, 배열 테이블 인것 같습니다.
table.c
/*
** table.c
** Module to control static tables
*/
char *rcs_table="$Id: table.c,v 2.1 1994/04/20 22:07:57 celes Exp $";
#include <stdlib.h>
#include <string.h>
#include "mm.h"
#include "opcode.h"
#include "hash.h"
#include "inout.h"
#include "table.h"
#include "lua.h"
//비교하는 두 문자열 첫 글자가 다르면 strcmp() 함수 호출을 하지 않고 바로 false를 리턴합니다.
//그런데 제가 알기로 strcmp() 함수 구현도 첫 글자부터 다르면 바로 리턴하거든요.
#define streq(s1,s2) (s1[0]==s2[0]&&strcmp(s1+1,s2+1)==0)
//MAXSYMBOL은 512이고 Symbol 타입으로 512개 배열을 선언했습니다.
#ifndef MAXSYMBOL
#define MAXSYMBOL 512
#endif
static Symbol tablebuffer[MAXSYMBOL] = {
{"type",{T_CFUNCTION,{lua_type}}},
{"tonumber",{T_CFUNCTION,{lua_obj2number}}},
{"next",{T_CFUNCTION,{lua_next}}},
{"nextvar",{T_CFUNCTION,{lua_nextvar}}},
{"print",{T_CFUNCTION,{lua_print}}},
{"dofile",{T_CFUNCTION,{lua_internaldofile}}},
{"dostring",{T_CFUNCTION,{lua_internaldostring}}}
};
Symbol *lua_table=tablebuffer;
Word lua_ntable=7;
//tablebuffer를 링크드 리스트로 구현?
/******아래 참조
typedef struct
{
char *name;
Object object;
} Symbol;
Symbol 구조체는 이렇게 생겼습니다. name과 object입니다.
tablebuffer 초기화 데이터를 보면 name에는 함수 이름이나 명령어 이름 같이 보이는 문자열이 있습니다.
Object는 함수 포인터입니다.
함수 포인터 7개를 넣었으므로 lua_ntable은 7입니다.
**************/
struct List
{
Symbol *s;
struct List *next;
};
//struct List는 Symbol 타입 자료 구조를 링크드 리스트로 만들려고 만든 구조체입니다.
//이 링크드 리스트 구조체에 tablebuffer를 하나씩 넣어서 링크드 리스트로 만듭니다.
//이미 tablebuffer가 배열이고 크기도 512로 한정되어 있는데 이걸 왜 굳이 링크드 리스트로 다시 만드는지 알 수 없 없음
static struct List o6={ tablebuffer+6, 0};
static struct List o5={ tablebuffer+5, &o6 };
static struct List o4={ tablebuffer+4, &o5 };
static struct List o3={ tablebuffer+3, &o4 };
static struct List o2={ tablebuffer+2, &o3 };
static struct List o1={ tablebuffer+1, &o2 };
static struct List o0={ tablebuffer+0, &o1 };
static struct List *searchlist=&o0;
#ifndef MAXCONSTANT
#define MAXCONSTANT 256
#endif
/* pre-defined constants need garbage collection extra byte */
//초기값으로 아래 8개 문자를 상수로 정의한다.
//버퍼의 [0]번째 값은 비워둔다.
//constantbuffer에는 [1]부터 넣는다?
static char tm[] = " mark";
static char ti[] = " nil";
static char tn[] = " number";
static char ts[] = " string";
static char tt[] = " table";
static char tf[] = " function";
static char tc[] = " cfunction";
static char tu[] = " userdata";
static char *constantbuffer[MAXCONSTANT] = {tm+1, ti+1,
tn+1, ts+1,
tt+1, tf+1,
tc+1, tu+1
};
char **lua_constant = constantbuffer;
Word lua_nconstant=T_USERDATA+1;
//위 코드의 주석을 봐도 그렇고, 상수 배열 초기값을 봐도 그렇고 첫 바이트 인덱스 위치를 비워둡니다.
//지난번에 읽었던 함수에서도 첫 바이트 인덱스를 마크용으로 비워두는 코드가 있었습니다.
//그걸 가비지 콜렉션 용으로 쓴다는 것 같습니다.
//루아의 데이터 타입 이름을 상수 배열 초기값으로 넣었습니다.
//상수 배열인데 예약어 관리도 같이 해주는 건가하는 생각이 듭니다.
//문자열 배열은 초기값이 없습니다. 그냥 lua_string 변수에 포인터를 넘기고 끝나네요.
#ifndef MAXSTRING
#define MAXSTRING 512
#endif
static char *stringbuffer[MAXSTRING];
char **lua_string = stringbuffer;
Word lua_nstring=0;
#define MAXFILE 20
char *lua_file[MAXFILE];
int lua_nfile;
#define markstring(s) (*((s)-1))
/* Variables to controll garbage collection */
Word lua_block=10; /* to check when garbage collector will be called */
Word lua_nentity; /* counter of new entities (strings and arrays) */
/*
** Given a name, search it at symbol table and return its index. If not
** found, allocate at end of table, checking oveflow and return its index.
** On error, return -1.
*/
int lua_findsymbol (char *s)
{
struct List *l, *p;
for (p=NULL, l=searchlist; l!=NULL; p=l, l=l->next)
if (streq(s,l->s->name))
{
//심볼 테이블에서 심볼을 찾으면 방금 찾은 심볼 위치를 searchlist에 저장해 뒀다가 다음에는 직전 검색에서 hit 했던 위치에서부터 심볼 검색을 다시 시작하는 것입니다.
//아마도 프로그래밍 언어론에 나오는 변수 지역성 이런것을 고려해서 직전에 검색한 심볼을 바로 이어서 다시 검색할 가능성이 많으니 시간을 줄이려고 코드를 위와 같이 만든것 같습니다.
//만약 심볼 테이블에 찾고자하는 심볼이 없으면 심볼 테이블에 심볼을 추가하고 갯수를 늘립니다.
if (p!=NULL)
{
p->next = l->next;
l->next = searchlist;
searchlist = l;
}
return (l->s-lua_table);
}
if (lua_ntable >= MAXSYMBOL-1)
{
lua_error ("symbol table overflow");
return -1;
}
s_name(lua_ntable) = strdup(s);
if (s_name(lua_ntable) == NULL)
{
lua_error ("not enough memory");
return -1;
}
s_tag(lua_ntable) = T_NIL;
p = malloc(sizeof(*p));
p->s = lua_table+lua_ntable;
p->next = searchlist;
searchlist = p;
return lua_ntable++;
}
/*
** Given a constant string, search it at constant table and return its index.
** If not found, allocate at end of the table, checking oveflow and return
** its index.
**
** For each allocation, the function allocate a extra char to be used to
** mark used string (it's necessary to deal with constant and string
** uniformily). The function store at the table the second position allocated,
** that represents the beginning of the real string. On error, return -1.
**
*/
//lua_findconstant() 함수는 lua_constant 배열에서 파라메터 s를 검색합니다.
//constant를 보통 상수라고 번역하는데, 루아 구현에서는 변수 이름이 lua_findconstant() 함수에 입력으로 들어갑니다.
//그럼 심볼은 뭐지?하는 의문이 바로 듭니다. 심볼에는 파라메터 이름이나 함수 이름이 들어갑니다.
int lua_findconstant (char *s)
{
int i;
for (i=0; i<lua_nconstant; i++)
if (streq(s,lua_constant[i]))
return i;
if (lua_nconstant >= MAXCONSTANT-1)
{
lua_error ("lua: constant string table overflow");
return -1;
}
{
char *c = calloc(strlen(s)+2,sizeof(char));
c++; /* create mark space */
lua_constant[lua_nconstant++] = strcpy(c,s);
}
return (lua_nconstant-1);
}
/*
** Traverse symbol table objects
*/
//lua_travsymbol() 함수는 심볼 테이블 배열을 순회하면서 파라메터로 넘어온 함수에 적용하는 것입니다.
//그런데 루아 1.1 소스 코드에서는 lua_markobject() 함수 하나만 사용합니다.
//lua_markobject() 함수는 Object 구조체에 mark를 1로 바꾸는 동작을 합니다.
void lua_travsymbol (void (*fn)(Object *))
{
int i;
for (i=0; i<lua_ntable; i++)
fn(&s_object(i));
}
/*
** Mark an object if it is a string or a unmarked array.
*/
void lua_markobject (Object *o)
{
if (tag(o) == T_STRING)
markstring (svalue(o)) = 1;
else if (tag(o) == T_ARRAY)
lua_hashmark (avalue(o));
}
/*
** Garbage collection.
** Delete all unused strings and arrays.
*/
//lua_pack() 함수는 가비지 컬랙션을 수행하는 함수입니다.
//함수 내부에서는 특별한 로직없이 다른 함수를 연달아 호출만 하는 배치(batch) 함수입니다.
//lua_travstack()과 lua_travsymbol()은 lua_markobject() 함수 포인터를 각각 스택과 심볼 테이블을 대상으로 돌리는 함수입니다.
//그리고 lua_stringcollector() 함수와 lua_hashcollector() 함수를 호출합니다.
//lua_hashcollector() 함수는 hash.h와 Hash.c 파일을 읽을 때 읽었습니다.
//그래서 지금은 lua_stringcollector() 함수만 읽어 보겠습니다.
//구현은 간단합니다. 마크용으로 비워둔 문자열의 첫 번째 바이트가 1이면 마크를 다시 0으로 바꾸고 lua_string 배열에 다시 쌓습니다. 만약 1이 아니면 해당 문자열 버퍼를 해제합니다.
//루아의 가비지 컬랙션은 이런식으로 동작하는 것 같습니다.
//모든 문자열은 lua_string 배열에 일단 들어가고 그 중 레퍼런스되는 문자열이나 심볼은 각각 심볼 테이블이나 스택에 포인터를 복사합니다.
//그리고 일정 시점마다 lua_pack() 함수를 돌려서 현재 레퍼런스가 살아 있는 포인터에는 표시를 합니다.
//그런 다음 lua_stringcollector() 함수와 lua_hashcollector() 함수를 돌려서 마크가 없는 포인터를 해제합니다.
void lua_pack (void)
{
/* mark stack strings */
lua_travstack(lua_markobject);
/* mark symbol table strings */
lua_travsymbol(lua_markobject);
lua_stringcollector();
lua_hashcollector();
lua_nentity = 0; /* reset counter */
}
/*
** Garbage collection to atrings.
** Delete all unmarked strings
*/
void lua_stringcollector (void)
{
int i, j;
for (i=j=0; i<lua_nstring; i++)
if (markstring(lua_string[i]) == 1)
{
lua_string[j++] = lua_string[i];
markstring(lua_string[i]) = 0;
}
else
{
free (lua_string[i]-1);
}
lua_nstring = j;
}
/*
** Allocate a new string at string table. The given string is already
** allocated with mark space and the function puts it at the end of the
** table, checking overflow, and returns its own pointer, or NULL on error.
*/
//lua_block이 10인데 문자열이 10개 새로 생길 때 마다 한 번씩 가비지 컬랙션을 수행하는 것으로 이해됩니다.
char *lua_createstring (char *s)
{
int i;
if (s == NULL) return NULL;
for (i=0; i<lua_nstring; i++)
if (streq(s,lua_string[i]))
{
free(s-1);
return lua_string[i];
}
if (lua_nentity == lua_block || lua_nstring >= MAXSTRING-1)
{
lua_pack ();
if (lua_nstring >= MAXSTRING-1)
{
lua_error ("string table overflow");
return NULL;
}
}
lua_string[lua_nstring++] = s;
lua_nentity++;
return s;
}
/*
** Add a file name at file table, checking overflow. This function also set
** the external variable "lua_filename" with the function filename set.
** Return 0 on success or 1 on error.
*/
//루아 파일을 하나씩 읽을 때마다 lua_file 배열 변수에 파일 이름을 추가합니다.
//루아 코드 파싱이 끝나면 lua_delfile을 호출합니다.
//lua_filename() 함수는 에러 상황에서 에러 메시지를 출력할 때 마지막으로 로딩한 파일 이름을 받을 때 사용합니다.
int lua_addfile (char *fn)
{
if (lua_nfile >= MAXFILE-1)
{
lua_error ("too many files");
return 1;
}
if ((lua_file[lua_nfile++] = strdup (fn)) == NULL)
{
lua_error ("not enough memory");
return 1;
}
return 0;
}
/*
** Delete a file from file stack
*/
int lua_delfile (void)
{
lua_nfile--;
return 1;
}
/*
** Return the last file name set.
*/
char *lua_filename (void)
{
return lua_file[lua_nfile-1];
}
/*
** Internal function: return next global variable
*/
void lua_nextvar (void)
{
int index;
Object *o = lua_getparam (1);
if (o == NULL)
{ lua_error ("too few arguments to function `nextvar'"); return; }
if (lua_getparam (2) != NULL)
{ lua_error ("too many arguments to function `nextvar'"); return; }
if (tag(o) == T_NIL)
{
index = 0;
}
else if (tag(o) != T_STRING)
{
lua_error ("incorrect argument to function `nextvar'");
return;
}
else
{
for (index=0; index<lua_ntable; index++)
if (streq(s_name(index),svalue(o))) break;
if (index == lua_ntable)
{
lua_error ("name not found in function `nextvar'");
return;
}
index++;
while (index < lua_ntable && tag(&s_object(index)) == T_NIL) index++;
if (index == lua_ntable)
{
lua_pushnil();
lua_pushnil();
return;
}
}
{
Object name;
tag(&name) = T_STRING;
svalue(&name) = lua_createstring(lua_strdup(s_name(index)));
if (lua_pushobject (&name)) return;
if (lua_pushobject (&s_object(index))) return;
}
}
반응형
Comments