Search code examples
lua

Need Help on db storequery in LUA


I'm currently trying to do a dbstorequery in LUA, but everytime i always got the error message "attempt to index a nil value"

Here is the detailed info:

  • I have an array of inputlist
  • From the array of inputlist, i will get info "status" and "name"
  • The information in "name" will be used to do matching from column of "TableEdoc" in table "Dataflow1"
  • The query result should be "id" which contain row number of the matching result
  • The query result will be only 1 result
  • Query result will be stored in variable "index"

Here is the script:

local number updatestatus = data.inputlist[0].status

local number updatename = data.inputlist[0].name

local index = db.storequery("SELECT 'id' FROM 'Dataflow1' where 'TableEdoc' = 'updatename'")

data.dataflow1[index].status = updatestatus

Here is my "Dataflow1" table:

enter image description here

Need help here as i totally noob in LUA.

Thanks so much in advance

Rusdi


Solution

  • There are several issues with your code. I would expect more in the code you haven't provided so better check everything again.

    Lua is dynamically typed. You don't have to give a type when you define a variable.

    local number updatestatus = data.inputlist[0].status
    
    local number updatename = data.inputlist[0].name
    

    is actually the same as

    local number = nil
    updatestatus = data.inputlist[0].status
    local number = nil
    updatename = data.inputlist[0].name
    

    I guess this was not what you intended to do.

    The error tells you that you're attempting to index a nil value. This doesn't make sense in Lua so it raises an error.

    You should find out which value is nil and fix that. You could for example simply print them. Maybe a typo? data.dataflow1 instead of data.Dataflow1

    A db request might not return any results. In that case most APIs return nil. You should check wether the result of your query is nil befor you use it.

    Your db screenshot does not show any entry that is 'updatename'. Assuming that you only have those 3 rows in your table you won't get a result.

    Also note that 'updatename' is the literal string updatename and not the content of your variable updatename.

    You have to insert the value of your variable into the query string.

    local query = string.format("SELECT 'id' FROM 'Dataflow1' where 'TableEdoc' = %q", updatename)
    local index = db.storequery(query)
    

    Are you sure it is storequery and not storeQuery?