2013-11-03 2 views
5

함수에 빈 값을 전달하려고했지만 실패했습니다. 여기 내 설정입니다.루아의 함수에 빈 변수를 전달하는 방법

function gameBonus.new(x, y, kind, howFast) -- constructor 
    local newgameBonus = { 
     x = x or 0, 
     y = y or 0, 
     kind = kind or "no kind", 
     howFast = howFast or "no speed" 
    } 
    return setmetatable(newgameBonus, gameBonus_mt) 
end 

"kind"를 전달하고 나머지를 처리하기를 원합니다. 처럼;

local dog3 = dog.new("" ,"" , "bonus","") 

또는 "howFast"만 전달하면됩니다.

unexpected symbol near ','

답변

5

nil, 당신이해야 루아에서 빈 대표하는 유형과 값, 그래서 대신 빈 문자열을 "" 또는 아무것도 통과하지의 :

local dog3 = dog.new(, , , "faster") 

내가 ""와없이 모두 시도, 오류를 제공 이런 nil 합격 : 마지막 nil 생략 할 수

local dog3 = dog.new(nil ,nil , "bonus", nil) 

참고. xfalsenil없는 둘 경우이다

if not x then x = 0 end 

가 기본값으로 x을 설정

x = x or 0 

가 동일하다, 예를 들어 발현 첫번째 파라미터 x 걸릴 0.

1
function gameBonus.new(x, y, kind, howFast) -- constructor 
    local newgameBonus = type(x) ~= 'table' and 
    {x=x, y=y, kind=kind, howFast=howFast} or x 
    newgameBonus.x = newgameBonus.x or 0 
    newgameBonus.y = newgameBonus.y or 0 
    newgameBonus.kind = newgameBonus.kind or "no kind" 
    newgameBonus.howFast = newgameBonus.howFast or "no speed" 
    return setmetatable(newgameBonus, gameBonus_mt) 
end 

-- Usage examples 
local dog1 = dog.new(nil, nil, "bonus", nil) 
local dog2 = dog.new{kind = "bonus"} 
local dog3 = dog.new{howFast = "faster"} 
관련 문제