Check, if scene object exist (without errors or warnings)

  • #1, by LebosteinTuesday, 30. June 2015, 16:14 5 years ago
    How I can check, if a scene object exist? The first method results in error, the second method prints a warning if the object "xyz" is not in the scene:
    testobj = game.CurrentScene.Objects["xyz"]
    testobj = getObject("Game.GameCurrentScene.SceneObjects[xyz]")
    1
    2
    3

    I need something like that, a safe test if the object exist before I use it:
    if "xyz" in game.CurrentScene.Objects then
    testobj = game.CurrentScene.Objects["xyz"]
    blabla....
    end
    1
    2
    3
    4
    5

    Key Killer

    598 Posts


  • #2, by SimonSTuesday, 30. June 2015, 17:11 5 years ago
    You can use the method even if it writes an error to the log.

    testobj = game.CurrentScene.Objects["xyz"]
    if testobj ~= nil then

    end
    1
    2
    3
    4
    5

    Thread Captain

    1333 Posts

  • #3, by LebosteinTuesday, 30. June 2015, 21:33 5 years ago
    @Simon, that is the problem.
    testobj = game.CurrentScene.Objects["xyz"]
    1
    2

    produces an ERROR. Is there no clean and safe method for this?

    Key Killer

    598 Posts

  • #4, by SimonSTuesday, 30. June 2015, 22:12 5 years ago
    If you're that concerned about it:

    function contains(arr, name)
    for i = 1, #arr do
    if arr[i]:getName()==name then
    return true
    end
    end
    return false
    end

    print(contains(game.CurrentScene.Objects, "Objekt7"))
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

    Thread Captain

    1333 Posts

  • #5, by LebosteinWednesday, 01. July 2015, 08:22 5 years ago
    Thanks!

    Which lua type is the game.CurrentScene.Objects list? A simple lua table?
    But if this is a lua table, Objects["xyz"] should return nil without an error if "xyz" not exist. Or is this error triggered by Visionaire and not by lua?

    Key Killer

    598 Posts

  • #6, by afrlmeWednesday, 01. July 2015, 12:41 5 years ago
    You can actually check the type yourself. See here.
    print( type(var) )
    1
    2

    I think quite a lot of the data structure fields in vs will return as table except when accessing specific fields. Characters / Objects / Scenes / Scene Objects etc should return tables as they contain additional fields inside of them.

    Objects["xyz"] would return a table because objects contain multiple fields inside of them such as position, offset, opacity, name, etc. etc.

    Imperator

    6808 Posts

Write post