개발시 펼쳐놓고 코딩하려고 정리.

절대 경로 ::

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
print("document==="..system.pathForFile("", system.DocumentsDirectory))
print("cache==="..system.pathForFile("", system.CachesDirectory))
print("temp==="..system.pathForFile("", system.TemporaryDirectory))

결과 (Android) ::
document===/data/data/com.wonhada.wonhadacorona/app_data/
cache===/data/data/com.wonhada.wonhadacorona/cache/Caches/
temp===/data/data/com.wonhada.wonhadacorona/cache/tmp/
resource는 접근 권한이 없으므로 에러남

결과 (iOS) ::
document===/var/mobile/Containers/Data/Application/270F51E3-77A1-4422-9E94-714E256485AA/Documents
cache===/var/mobile/Containers/Data/Application/270F51E3-77A1-4422-9E94-714E256485AA/Library/Caches/Caches
temp===/private/var/mobile/Containers/Data/Application/270F51E3-77A1-4422-9E94-714E256485AA/tmp
resource===/var/containers/Bundle/Application/0F8F9E57-6934-4277-ACBB-50F35AAE9C47/App.app

기본 Class 형태 ::

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
--##############################  Main Code Begin  ##############################--
local Class = {}

--==========================--
--
-- Private Methods
--
--==========================--

--==========================--
--
-- Public Methods
--
--==========================--

Class.create = function()
    local mainG = display.newGroup() -- mainGroup

    -- local 변수정의

    -- UI 생성
    local function createUI()
       
    end
    createUI()

    return mainG
end

return Class
--##############################  Main Code End  ##############################--

컴포저의 view 참조하기 ::

1
2
3
4
5
6
-- local currSceneName = composer.getSceneName("current")
local currSceneName = "scenes.FooScene"
composer.gotoScene( currSceneName, composerOptions )
-- composer.showOverlay( currSceneName, composerOptions )
local currScene = composer.getScene(currSceneName)
print(currScene.view.GGG)

싱글턴 패턴 ::

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
--##############################  Main Code Begin  ##############################--
local Class = {}

local _instance = nil

--==========================--
--
-- Public Methods
--
--==========================--

Class.getInstance = function ()
    if _instance then return _instance end
   
    print("create!!")
   
    _instance = display.newGroup()
    _instance.name = math.random()
   
    function _instance:getName()
        return _instance.name;
    end
   
    return _instance
end

return Class
--##############################  Main Code End  ##############################--

옵션으로 텍스트 생성하기 ::

1
2
3
4
5
6
7
8
9
10
11
12
13
local txtOptions =
{
    parent = group,
    text = "WonHada.com",
    x = 0,
    y = 0,
    width = 200,
    height = 30,
    font = native.systemFont, -- font = "DINBol",
    fontSize = 25,
    align = "center"
}
local txt = display.newText(txtOptions)

String:Split() 확장 ::

1
2
3
4
5
6
function string:split(sep)
    local sep, fields = sep or ":", {}
    local pattern = string.format("([^%s]+)", sep)
    self:gsub(pattern, function(c) fields[#fields+1] = c end)
    return fields
end

테이블뷰 생성 ::

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
local widget = require("widget")

--*****  TableView  *****--
local function onRowRender(e)
    local row = e.row -- row.params, row.index, row.contentWidth, row.contentHeight
    local params = row.params
    local cWidth = row.contentWidth
    local cHeight = row.contentHeight
end

local function onRowTouch(e)
    -- e.phase == ("tap", "press", "release", "swipeLeft", "swipeRight"), e.target.index
end

-- local prevTouchX, prevTouchY
local function scrollListener(e)
    -- e.phase == ("began", "moved", "ended"), e.limitReached, e.direction == ("up", "down")
--[[ 일반적인 이벤트 형태로 만들기 위해 작성한 코드
    if e.phase == "began" then
        if prevTouchX == nil then -- 처음 began
            display.getCurrentStage():setFocus(e.target)
            prevTouchX, prevTouchY = e.x, e.y
        elseif prevTouchX ~= e.x then e.phase = "moved" end -- 스크롤되지 않을 때는 항상 began이 나오므로 강제로 바꿔줌
    end
   
    if prevTouchX == nil then return end -- 이렇게 처리를 안하면 외부에서 누르고 들어왔을 때 이벤트 발생
   
    local tableView = (e.target.name == nil and e.target.parent or e.target.parent.parent)
    local mainG = tableView.parent
    mainG:dispatchEvent({name="touched", type="tableView", target=tableView, touchEvent=e})
   
    if e.phase == "ended" then
        prevTouchX, prevTouchY = nil, nil
        display.getCurrentStage():setFocus(nil)
    end
]]

end

local createTableView = function (_width, _height)
    local tv = widget.newTableView
    {
        width = _width,
        height = _height,
        noLines = true,
        rowTouchDelay = 40,
        hideScrollBar = true,
        hideBackground = true,
--      backgroundColor = { 0, 0, 0, 1 },
        onRowRender = onRowRender,
        onRowTouch = onRowTouch,
        listener = scrollListener
    }
   
    return tv
end
--*****  TableView  *****--

local tableView = createTableView(320, 480)
tableView:insertRow(
    {
        isCategory = false,
--        rowHeight = 50,
        rowColor = { default={ 0, 0, 0, 0 }, over={ 0, 0, 0, 0 } }, -- onRowTouch 이벤트를 등록해야 작동함
--        lineColor = { 0, 0, 0, 1 },
        params = nil
    }
)

폴더의 모든 파일 삭제 (최상위 폴더를 삭제할 경우 마지막 인자에 true) ::

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
local lfs = require("lfs")
local function _removeAllFiles(dir, depth, isDeleteRoot)
    if dir == nil then return end
   
    depth = depth or 0
    isDeleteRoot = isDeleteRoot or false
   
    local separate = "/"
    if string.find(dir, "\") ~= nil then separate = "\" end
   
    local results, iter = lfs.dir (dir)
    local file = iter:next()
    while file do
        if tostring(file) ~= "
." and tostring(file) ~= ".." then
            local fullPath = dir..separate..file
            if (lfs.attributes(fullPath, "
mode") == "directory") then -- 디렉토리
                local nextDepth = depth + 1
                _removeAllFiles(fullPath, nextDepth)
            else -- 파일
                os.remove(fullPath)
            end
        end
        file = iter:next()
        if (isDeleteRoot == true or depth > 0) and file == nil then lfs.rmdir(dir) end
    end
end
_removeAllFiles(system.pathForFile("
", system.TemporaryDirectory), 0, false) -- 두 번째 인자는 무조건 0

Hex to RGB(percent) ::

1
2
3
4
5
6
7
8
9
10
11
12
-- Hex code를 RGB 퍼센트로 변환
local function hexToPercent(hex)
    local r = tonumber(hex:sub(1, 2), 16) / 255
    local g = tonumber(hex:sub(3, 4), 16) / 255
    local b = tonumber(hex:sub(5, 6), 16) / 255
    local a = 255 / 255
    if #hex == 8 then a = tonumber(hex:sub(7, 8), 16) / 255 end
    return r, g, b, a
end

print(hexToPercent("FFFFFF")) -- 1 1 1 1
print(hexToPercent("FFFFFF80")) -- 1 1 1 0.50196078431373

배경에 주로 사용하는 코드(가로 모드일 때) ::

1
2
3
4
5
6
local bg = display.newImage("images/bg.png", 0, 0)

local scaleFactor = display.actualContentHeight / bg.height

bg.width, bg.height = bg.width * scaleFactor, bg.height * scaleFactor
bg.x = (display.actualContentWidth * 0.5) - (bg.width * 0.5)

기기별 화면 사이즈 (기본 템플릿 사용시) ::
http://bit.ly/2BxwdKB