Search code examples
lualua-table

LUA|MTA attempt to index global "zoneName" (a nil value)


I'm encountering a problem in a Lua script that I'm learning from (i am new to Lua) this error got me heavily confused, when I run the code it gives me this following error:

attempt to index global "zoneName" (a nil value)

this is my code:

    local zoneName = zoneName:gsub ( "'", "" )  
    if dbExec ( handler, "INSERT INTO `safeZones` (`rowID`, `zoneName`, `zoneX`, `zoneY`, `zoneWidth`, `zoneHeight`) VALUES (NULL, '".. tostring ( zoneName ) .."', '".. tostring ( zoneX ) .."', '".. tostring ( zoneY ) .."', '".. zoneWidth .."', '".. zoneHeight .."');" ) then 
    createSafeZone (            {               [ "zoneName" ] = zoneName,              [ "zoneX" ] = zoneX,                [ "zoneY" ] = zoneY,                [ "zoneWidth" ] = zoneWidth,                [ "zoneHeight" ] = zoneHeight           }       )      
    outputDebugString ( "Safe Zones: Safe zone created name: ".. tostring ( zoneName ) ) 
    return true 
       else        
           return false, "Unable to create the safe zone" 
           end

Solution

  • You reference zoneName already in it's definition, you code equals to

    local zoneName = nil:gsub("'", "")

    hence the error (zoneName is not yet defined when Lua tries to execute zoneName:gsub()).

    Either define zoneName before the gsub() call or use string.gsub()