Search code examples
sqlitegodotgdscript

Godot: Im setting a variable but its acting as a pointer


var t = db.query_result

Then I use this in a for with multiple other queries which change the value of t, but I want to set it at the value of my first query? How do I set t at db.query_result and make it not change afterwards when I make other queries?

func setTuto1():#
db.open_db()
db.query("select ID from currentTutorialMap where LandTextureType = 'Stone0';")
var t = db.query_result
print(t)
print(t.size())
print(t[1]["ID"])
for i in range(0, t.size()):
    var x = rng.randi_range(0, 6)
    if x==0:
        db.query("update currentTutorialMap set LandTextureIndex = 10 where ID == %d;" % t[i]["ID"])
    elif (x==1 or x==2):
        db.query("update currentTutorialMap set LandTextureIndex = 9 where ID == %d;" % t[i]["ID"])
    elif (x==3 or x==4):
        db.query("update currentTutorialMap set LandTextureIndex = 11 where ID == %d;" % t[i]["ID"])
    elif (x==5 or x==6):
        db.query("update currentTutorialMap set LandTextureIndex = 12 where ID == %d;" % t[i]["ID"])

Solution

  • The variable t is local to your method (func). If you want it to keep its value, make it a field (declare it outside any func, the guidelines suggest to do that at the top of the script).

    And if you just want the first result, and not overwrite it, you can have a bool variable, set to false by default. When you write t, you set it to true. That allows you to check if you have already set t.

    Something like this:

    var _is_t_set := false
    var _t
    
    func setTuto1():
        if _is_t_set:
            # we have been here before
            # do whatever you do in this case
            pass
        else:
            # first time we are here
            db.open_db()
            db.query("blah blah blah")
            _t = db.query_result
            _is_t_set = true # so we do not enter here again
    

    Alternatively you could use null. Although double check if db.query_result can be null.

    Something like this:

    var _t = null
    
    func setTuto1():
        if _t != null:
            # we have been here before
            # do whatever you do in this case
            pass
        else:
            # first time we are here
            db.open_db()
            db.query("blah blah blah")
            _t = db.query_result
    

    And, by the way, use prepared statements.