2013-10-13 1 views
5

사용자 정의 변수 유형 ("유형"메소드를 사용하여 사용자 정의 유형으로 감지 될 수 있음)을 가질 수있는 lua의 라이브러리/기능을 찾고 있습니다. 나는 JSON 인코더/디코더에 사용자 정의 유형 "json"을 만들려고합니다. 루아 혼자서 할 수있는 솔루션이 필요합니다.사용자 정의 변수 유형 Lua

답변

9

당신은 새로운 루아 타입을 만들 수는 없지만, 메타 테이블과 테이블을 사용하여 생성을 모방 할 수 있습니다.

local frobnicator_metatable = {} 
frobnicator_metatable.__index = frobnicator_metatable 

function frobnicator_metatable.ToString(self) 
    return "Frobnicator object\n" 
     .. " field1 = " .. tostring(self.field1) .. "\n" 
     .. " field2 = " .. tostring(self.field2) 
end 


local function NewFrobnicator(arg1, arg2) 
    local obj = { field1 = arg1, field2 = arg2 } 
    return setmetatable(obj, frobnicator_metatable) 
end 

local original_type = type -- saves `type` function 
-- monkey patch type function 
type = function(obj) 
    local otype = original_type(obj) 
    if otype == "table" and getmetatable(obj) == frobnicator_metatable then 
     return "frobnicator" 
    end 
    return otype 
end 

local x = NewFrobnicator() 
local y = NewFrobnicator(1, "hello") 

print(x) 
print(y) 
print("----") 
print("The type of x is: " .. type(x)) 
print("The type of y is: " .. type(y)) 
print("----") 
print(x:ToString()) 
print(y:ToString()) 
print("----") 
print(type("hello!")) -- just to see it works as usual 
print(type({})) -- just to see it works as usual 

출력 :

 
table: 004649D0 
table: 004649F8 
---- 
The type of x is: frobnicator 
The type of y is: frobnicator 
---- 
Frobnicator object 
    field1 = nil 
    field2 = nil 
Frobnicator object 
    field1 = 1 
    field2 = hello 
---- 
string 
table 

물론 예제는 단순하고 루아에서 객체 지향 프로그래밍에 대해 할 말이 많은 일들이있다 예를 들어. 다음 참조 자료가 유용 할 수 있습니다.

+0

여기서 type() 함수에 대해 일반적으로 클래스 이름을 설명하는 metatable에 __type 필드를 구현합니다. 그런 다음 type은 항상 모든 클래스에 유용한 값입니다. – Zeksie

+0

@ Zeksie 그래, 그건 확실히 선택 사항이야. 제가 말했듯이 루아에서는 OOP에 관해서 더 많은 이야기가 있습니다. –

+0

맞춤 변수 유형을 만드는 함수를 만들 수 있습니까? 예를 들어 :'jsonCode = { "json text here"} varType (jsonCode, "json")'은 커스텀 타입''json "'을 가진 단순히''jsonCode''를 반환 할 것입니다. 'tostring (jsonCode)'는 단지''jsonCode [1]'을 반환 할 것이다 (이 경우''json text here "'와 같을 것이다). 여기에있는 2 값 시스템을 구현하는 것을 귀찮게하지 마십시오. 단 하나의 값을 가진 테이블에서만 사용할 것입니다. – tupperkion

5

C API가 아닌 사용자가 원하는 것은 가능하지 않습니다. 루아에는 오직 내장 타입 만 있고, 더 추가 할 방법은 없습니다. 그러나 메타 메소드와 테이블을 사용하면 매우에 가까운 테이블을 다른 언어의 사용자 정의 유형/클래스에 접근 할 수 있습니다 (함수 작성). 예를 들어 Programming in Lua: Object-Oriented Programming을 참고하십시오 (그러나 책은 Lua 5.0 용으로 작성되었으므로 일부 세부 사항이 변경되었을 수도 있습니다).

관련 문제