Here an example Code from my Project:
Main Function:
loadImage(path, parentGrp)
– path -> Path to your image (In this example an PNG File in Folder “assets/”)
– parentGrp -> parent DisplayGroup the image will insert (OPTIONAL)
– return-value is the DisplayObject and hasError (BOOLEAN)
If an error happen:
If the load process has an error, the function return a DisplayObject (white rectangle).
The advantage the source-code will not directly crash later. You get a the visual feedback and error log feedback.
Already an error, no double outputs:
local hasImageDir = {}
hasImageDir save the state if already got an invalid Image, to avoid double log errors outputs.
---@type table<string, boolean>
local hasImageDir = {}
---@return DisplayObject, boolean
---@param parentGrp DisplayGroup
---@param path string
function loadImage(path, parentGrp)
if (path ~= nil) then
local myImagePath = "assets/" .. path .. ".png" -- < HERE complete the asset-path and ending.
---@type DisplayObject
local myImage
local hasError = false
if (hasImageDir[myImagePath] == nil or hasImageDir[myImagePath] == true) then
myImage = display.newImage(myImagePath)
if (hasImageDir[myImagePath] ~= nil) then
hasImageDir[myImagePath] = not (myImage == nil)
end
if (myImage == nil) then
print("assetManager <loadImage> not found:", myImagePath) --- here you can add your error log profiler
hasError = true
myImage = display.newRect(5, 5, 5, 5)
end
else
hasError = true
myImage = display.newRect(5, 5, 5, 5)
end
if (parentGrp ~= nil and parentGrp.insert ~= nil) then
parentGrp:insert(myImage)
end
return myImage, hasError
else
print("assetModel <loadImage> param path is NIL!")
myImage = display.newRect(5, 5, 5, 5)
if (parentGrp ~= nil and parentGrp.insert ~= nil) then
parentGrp:insert(myImage)
end
return display.newRect(5, 5, 5, 5), true
end
end
---@type DisplayGroup
local knightGrp = display.newGroup()
local plateLeft, hasError = loadImage("knight/plate_left")
knightGrp:insert(plateLeft)
print("image plateLeft has Error:", hasError)
local plateRight, hasError = loadImage("knight/plate_right", plateRightGrp)
print("image plateRight has Error:", hasError)