Lua Objects

Gedemon

Modder
Super Moderator
Joined
Oct 4, 2004
Messages
11,582
Location
France
Lua reference documents (newer to older)


old post:
Spoiler :

See the spreadsheets here for a dump of functions in player, unit, city, plot and some of the manager and configuration, as well as a partial dump of _G, and all the events:
https://docs.google.com/spreadsheets/d/1HQSUOmw_pI8dNSr1kmun4qAHj6SsOVfa1vGTbk5mVvs/edit#gid=0

It was made before the fall patch, and shows the difference between what's available in script and UI contexts..


Edit: I wasn't able to edit this since some time, if you are a modder and want to help by adding missing methods or arguments, just send me a PM with your google account name, and I'll add you.

Edit 2: I keep the old link for reference, but you really should use this table now (not my work)
https://docs.google.com/spreadsheets/d/1hQ8zlEHl1nfjCWvKqOlkDACezu5-igfQkVcOxeE_KG0/edit?usp=sharing
 
Last edited:
Here is the code used to create the dumps in the Firetuner:
Spoiler :
Code:
local player = Players[0]
local unit = nil
local playerUnits = player:GetUnits()
for i, u in playerUnits:Members() do
    if u then
        unit = u
    end
end
local pConfig = PlayerConfigurations[0]
local city = nil
local playerCities = player:GetCities()
for i, c in playerCities:Members() do
    if c then
        city = c
    end
end
local Plot = Map.GetPlot(0,0)
local GetBarbarianManager = nil
local GetFalloutManager = nil
local GetGossipManager = nil
local GetQuestsManager = nil
local GetTradeManager = nil
if Game.GetBarbarianManager then GetBarbarianManager = Game.GetBarbarianManager() end
if Game.GetFalloutManager then GetFalloutManager = Game.GetFalloutManager() end
if Game.GetGossipManager then GetGossipManager = Game.GetGossipManager() end
if Game.GetQuestsManager then GetQuestsManager = Game.GetQuestsManager() end
if Game.GetTradeManager then GetTradeManager = Game.GetTradeManager() end
local seenO = {}
local seenT = {}
listDump = {
    Achievements = Achievements,
    AutoplayManager = AutoplayManager,
    Calendar = Calendar,
    Cities = Cities,
    CityManager = CityManager,
    City = city,
    CombatManager = CombatManager,
    ContextPtr = ContextPtr,
    DealManager = DealManager,
    DiplomacyManager = DiplomacyManager,
    Game = Game,
    GameConfiguration = GameConfiguration,
    GameEffects = GameEffects,
    GetUnitStats = GetUnitStats,
    GameGetBarbarianManager = GetBarbarianManager,
    GameGetFalloutManager = GetFalloutManager,
    GameGetGossipManager = GetGossipManager,
    GameGetQuestsManager = GetQuestsManager,
    GameGetTradeManager = GetTradeManager,
    IconManager = IconManager,
    InstanceManager = InstanceManager,
    Locale = Locale,
    MapConfiguration = MapConfiguration,
    Map = Map,
    NotificationManager = NotificationManager,
    Options = Options,
    PlayerConfigurations = pConfig,
    PlayerManager = PlayerManager,
    PlayerVisibilityManager = PlayerVisibilityManager,
    Players = player,
    Plot = Plot,
    TTManager = TTManager,
    UIManager = UIManager,
    UITutorialManager = UITutorialManager,
    Unit = unit,
    UnitManager = UnitManager,
    Units = Units,
    UserConfiguration = UserConfiguration,
    }

listExceptionStr = {
    "IsNone",
    "ToPlot",
    "ToArea",
    "GetDiplomaticState",
    "HasProductionProgress",
    "ToolTip",
    "HasBeenPlaced",
    "GetAvailableProductionType",
    "GetTurnsLeft",
    "GetName",
    "GetScienceYieldToolTip",
    "GetPlayerName",
    "GetLeaderName",
    "Name",
    "Description",
    "Text",
    "Password",
    "GetNextEscapingSpyID",
    "Advice",
    "IsResourceExtractableAt",
    "Tooltip",
    "GetNextPursuedSpyID",
    "GetTurnFromIndex",
    "GetTurn",
    "GetNthOffMapSpy",
    "GetPlayerFromIndex",
    "FromIndex",
    "GetDiplomaticActionCost",
    "Turn",
    "Level",
    "GetDiplomatic",
    "GetCities",
    "GetStartingPlot",
    "GetActiveQuestReward",
    }
function canTest(functionName)
    local bCanTest = false
    local get = string.find(functionName, "Get")
    --local is = string.find(functionName, "Is")
    --local has = string.find(functionName, "Has")
    if get == 1 or is == 1 or has == 1 then
        bCanTest = true
    end
    for k, str in pairs(listExceptionStr) do
        if string.find(functionName, str) then
            return false
        end
    end
    return bCanTest
end
function dumpO(object,i)
    seenO[object]=true
    local s={}
    local n=0
    local meta = getmetatable(object).__index
    if type(meta)=="function" then meta = getmetatable(object).__index() end
    if not meta then return end
    for k, v in pairs(meta) do
        print(i,k)
        if type(v)=="table" and not seenT[v] then
            dumpT(v,i.."\t")
        end
        if type(v)=="function" then
            object.f = object[k]
            local value = nil
            if canTest(tostring(k)) then
                value = object:f()
                --print(i.."\t - ".."return value :", value)
            end
            if getmetatable(v) and getmetatable(v).__index and not seenO[v] then
                dumpO(v,i.."\t")
            end
            if value and getmetatable(value) and getmetatable(value).__index and not seenO[value] then
                dumpO(value,i.."\t")
            end
            if value and type(value)=="table" and not seenT[value] then
                dumpT(value,i.."\t")
            end
        end
    end;
end
function dumpT(table,i)
    seenT[table]=true
    local s={}
    local n=0
    for k in pairs(table) do
        n=n+1 s[n]=k
    end
    for k,v in ipairs(s) do
        print(i,v)
        v=table[v]
        if type(v)=="table" and not seenT[v] then
            dumpT(v,i.."\t")
        end
    end
end
function dumpAll()
    local contextName = "Script"
    if ContextPtr and ContextPtr.GetID then contextName = ContextPtr:GetID() end
    print("-----------------------------------------------------------------------------------------------------")
    print("-----------------------------------------------------------------------------------------------------")
    print("-- STARTING DUMP FROM CONTEXT = ".. Locale.ToUpper(contextName))
    print("-----------------------------------------------------------------------------------------------------")
    print("-----------------------------------------------------------------------------------------------------")
    local a = {}
    for n in pairs(listDump) do table.insert(a, n) end
    table.sort(a)
    for i,k in ipairs(a) do
        local v = listDump[k]
        local i = ""
        if type(v)=="function" then
            local value = v()
            print("return value :" .. value)
            if getmetatable(v) and getmetatable(v).__index then
                dumpO(v,i.."\t")
            end
            if getmetatable(value) and getmetatable(value).__index then
                dumpO(value,i.."\t")
            end
            if type(value)=="table" then
                dumpT(value,i.."\t")
            end
        end
        if getmetatable(v) and getmetatable(v).__index then
            print("--- object:", k)
            dumpO(v,i)
            print("--- ")
            print("--------------------------------------")
        end
        if type(v)=="table" then
            print("--- table:", k)
            dumpT(v,i)
            print("--- ")
            print("--------------------------------------")
        end
    end
end
dumpAll()

And the code I use to get the arguments values of all events:
Spoiler :

Code:
local maxCall = 50
local seen = {}
function dump(t,i)
    seen[t]=true
    local s={}
    local n=0
    for k, v in pairs(t) do
        print(i,k, v)
        if type(v)=="table" and not seen[v] then
            dump(v,i.."\t\t")
        end
    end
end

function getEventArguments(...)
    local args = {...}
    if args then
        print("---------------------------------------------------------------------------------- Start <")
        print("num arguments = " .. #args)
        print(unpack({...}))    
        for i = 1, #args do
            if type(args[i])== "table" then
                print("--------------- "..tostring(args[i]).." ---------------");
                dump(args[i], "");
                print();
            end
        end
        print("------------------------------------------------------------------------------------ End >");
        print();
    else 
        print("---------------------------------------------------------------------------------- Start <")
        print("No arguments...")
        print("------------------------------------------------------------------------------------ End >");
        print();
    end
end

local eventslist = {
    -- GameCoreEvent
    "AnarchyBegins",
    "AnarchyEnds",
    "BeliefAdded",
    "BuildingAddedToMap",
    "BuildingChanged",
    "BuildingRemovedFromMap",
    "CapitalCityChanged",
    "CityAddedToMap",
    "CityCommandStarted",
    "CityDefenseStatusChanged",
    "CityFocusChanged",
    "CityInitialized",
    "CityLiberated",
    "CityMadePurchase",
    "CityPopulationChanged",
    "CityProductionChanged",
    "CityProductionCompleted",
    "CityProductionUpdated",
    "CityProjectCompleted",
    "CityReligionChanged",
    "CityReligionFollowersChanged",
    "CityRemovedFromMap",
    "CitySiegeStatusChanged",
    "CityTileOwnershipChanged",
    "CityUnitsChanged",
    "CityVisibilityChanged",
    "CityWorkerChanged",
    "CivicBoostTriggered",
    "CivicChanged",
    "CivicCompleted",
    "CivicQueueChanged",
    "CivicsUnlocked",
    "Combat",
    "CultureChanged",
    "CultureYieldChanged",
    "DiplomacyDealEnacted",
    "DiplomacyDealExpired",
    "DiplomacyDeclareWar",
    "DiplomacyIncomingDeal",
    "DiplomacyMakePeace",
    "DiplomacyMeet",
    "DiplomacyMeetMajorMinor",
    "DiplomacyMeetMajors",
    "DiplomacyRefusePeace",
    "DiplomacyRelationshipChanged",
    "DiplomacySessionClosed",
    "DiplomacyStatement",
    "DistrictAddedToMap",
    "DistrictBuildProgressChanged",
    "DistrictCombatChanged",
    "DistrictDamageChanged",
    "DistrictPillaged",
    "DistrictRemovedFromMap",
    "DistrictUnitsChanged",
    "DistrictVisibilityChanged",
    "EndTurnBlockingChanged",
    "EndTurnDirty",
    "FaithChanged",
    "FeatureAddedToMap",
    "FeatureChanged",
    "FeatureRemovedFromMap",
    "GoodyHutReward",
    "GovernmentChanged",
    "GovernmentPolicyChanged",
    "GovernmentPolicyObsoleted",
    "GreatPeoplePointsChanged",
    "GreatPeopleTimelineChanged",
    "GreatWorkCreated",
    "GreatWorkMoved",
    "ImprovementActivated",
    "ImprovementAddedToMap",
    "ImprovementChanged",
    "ImprovementOwnershipChanged",
    "ImprovementRemovedFromMap",
    "ImprovementVisibilityChanged",
    "InfluenceChanged",
    "InfluenceGiven",
    "LevyCounterChanged",
    "LocalPlayerChanged",
    "LocalPlayerTurnBegin",
    "LocalPlayerTurnEnd",
    "MapYieldsChanged",
    "NationalParkAdded",
    "NaturalWonderRevealed",
    "NotificationAdded",
    "NotificationDismissed",
    "NotificationRefreshRequested",
    "ObjectPairing",
    "OnAiAdvisorUpdated",
    "PantheonFounded",
    "PhaseBegin",
    "PhaseEnd",
    "PlayerBordersChanged",
    "PlayerDefeat",
    "PlayerDestroyed",
    "PlayerEraChanged",
    "PlayerOperationComplete",
    "PlayerTurnActivated",
    "PlayerTurnDeactivated",
    --"PlayerVictory",
    "PlotMarkerChanged",
    "PlotVisibilityChanged",
    "PlotYieldChanged",
    "QuestChanged",
    "ReligionFounded",
    "RemotePlayerTurnBegin",
    "RemotePlayerTurnEnd",
    "ResearchChanged",
    "ResearchCompleted",
    "ResearchQueueChanged",
    "ResearchYieldChanged",
    "ResourceAddedToMap",
    "ResourceChanged",
    "ResourceRemovedFromMap",
    "ResourceVisibilityChanged",
    "RouteAddedToMap",
    "RouteChanged",
    "RouteRemovedFromMap",
    "SpyAdded",
    "SpyMissionUpdated",
    "SpyRemoved",
    "SpyUpdated",
    "StatusMessage",
    "TeamVictory",
    "TechBoostTriggered",
    "TerrainTypeChanged",
    "TradeRouteActivityChanged",
    "TradeRouteAddedToMap",
    "TradeRouteCapacityChanged",
    "TradeRouteRangeChanged",
    "TradeRouteRemovedFromMap",
    "TreasuryChanged",
    "TurnBegin",
    "TurnEnd",
    "UnitActivityChanged",
    "UnitAddedToMap",
    "UnitAirlifted",
    "UnitArtifactChanged",
    "UnitCaptured",
    "UnitChargesChanged",
    "UnitCommandStarted",
    "UnitDamageChanged",
    "UnitEmbarkedStateChanged",
    "UnitEnterFormation",
    "UnitExitFormation",
    "UnitFormArmy",
    "UnitFormCorps",
    "UnitFortificationChanged",
    "UnitGreatPersonActivated",
    "UnitGreatPersonChanged",
    "UnitGreatPersonCreated",
    "UnitKilledInCombat",
    "UnitMoveComplete",
    "UnitMoved",
    "UnitMovementPointsChanged",
    "UnitMovementPointsCleared",
    "UnitMovementPointsRestored",
    "UnitOperationAdded",
    "UnitOperationDeactivated",
    "UnitOperationSegmentComplete",
    "UnitOperationStarted",
    "UnitOperationsCleared",
    "UnitPromoted",
    "UnitPromotionAvailable",
    "UnitRemovedFromMap",
    "UnitTeleported",
    "UnitUpgraded",
    "UnitVisibilityChanged",
    "WMDCountChanged",
    "WMDDetonated",
    "WMDFalloutChanged",
    "WMDFalloutVisibilityChanged",
    "WonderCompleted",
    "WorldTextMessage",
    -- LocalMachineEvent
    "ARXOrientationChanged",
    "ARXTap",
    "AchievementProgress",
    "AchievementUnlocked",
    "Begin2KLoginProcess",
    "BeginGameView",
    "BeginMy2KLinkAccountProcess",
    "BeginWonderReveal",
    "Camera_Updated",
    "CloudGameInfoUpdated",
    "CloudGameJoinResponse",
    "CloudGameListUpdated",
    "EndGameView",
    "EndWonderReveal",
    "ExitToMainMenu",
    "FiraxisLiveActivate",
    "FrontEndPopup",
    "GameConfigChanged",
    "HideLeaderScreen",
    "InputActionTriggered",
    "InputGestureRecorded",
    "LeaderAnimationChanged",
    "LeaderAnimationComplete",
    "LeaderScreenFinishedLoading",
    "LeaveGameComplete",
    "ModStatusUpdated",
    "MultiplayerChat",
    "MultiplayerGameAbandoned",
    "MultiplayerGameLastPlayer",
    "MultiplayerGameListClear",
    "MultiplayerGameListComplete",
    "MultiplayerGameListUpdated",
    "MultiplayerHostMigrated",
    "MultiplayerJoinGameComplete",
    "MultiplayerJoinRoomAttempt",
    "MultiplayerJoinRoomComplete",
    "MultiplayerJoinRoomFailed",
    "MultiplayerPingTimesChanged",
    "MultiplayerPlayerConnected",
    "MultiplayerPostPlayerDisconnected",
    "MultiplayerPrePlayerDisconnected",
    "MultiplayerSnapshotProcessed",
    "My2KActivate",
    "My2KLinkAccountResult",
    "OptionChangeRequiresAppRestart",
    "OptionChangeRequiresGameRestart",
    "OptionChangeRequiresResolutionAck",
    "OptionChanged",
    "OptionsReset",
    "OptionsReverted",
    "OptionsSaved",
    "PlayerInfoChanged",
    "ShowLeaderScreen",
    "SteamFriendsPresenceUpdated",
    "SteamFriendsStatusUpdated",
    "SteamServersConnected",
    "SteamServersDisconnected",
    "TurnTimerUpdated",
    "UpdateGraphicsOptions",
    "UserAcceptsEULA",
    "UserAcceptsOutdatedDriver",
    "UserAcceptsUnknownDevice",
    "UserConfirmedClose",
    "UserRequestClose",
    "WorldRenderViewChanged",
    -- SequenceEvent
    "AppInitComplete",
    "GameViewStateDone",
    "LoadGameViewStateDone",
    "LoadScreenClose",
    "LoadScreenContentReady",
    "MainMenuStateDone",
    -- SerialEvent
    "AfterGameplayContentChange",
    "AfterGameplayContentConfigure",
    "AllCitiesDeselected",
    "AllDistrictsDeselected",
    "AllUnitsDeselected",
    "AutomationTestComplete",
    "BeforeGameplayContentChange",
    "BeforeGameplayContentConfigure",
    "BeforeMultiplayerInviteProcessing",
    "CitySelectionChanged",
    "CombatVisBegin",
    "CombatVisEnd",
    "CycleUnitSelectionRequest",
    "DemoExit",
    "DemoTurnLimitReached",
    "DistrictSelectionChanged",
    "FinishedGameplayContentChange",
    "FinishedGameplayContentConfigure",
    "GameConfigurationParameterChanged",
    "GameConfigurationRebuilt",
    "GameConfigurationResolved",
    "GameCoreEventPlaybackComplete",
    "GameCoreEventPublishComplete",
    "InterfaceModeChanged",
    "LensFocusHex",
    "LensLayerOff",
    "LensLayerOn",
    "LensUnFocusHex",
    "LoadCanceled",
    "LoadComplete",
    "MapMaxMajorPlayersChanged",
    "MultiplayerGameInvite",
    "MultiplayerGameLaunched",
    "PreTurnBegin",
    "RequestLoad",
    "RequestSave",
    "SaveCanceled",
    "SaveComplete",
    "SubscriptionDownloadStatus",
    "UnitSelectionChanged",
    "UnitSimPositionChanged",
    "UserOptionChanged",
    "VisualStateRestored",
    -- UIEvent
    "DragCamera",
    "SystemUpdateUI",
    -- New
}

local gameEventsList = {
    "CityBuilt",
    "CityConquered",
    "OnCityPopulationChanged",
    "OnFaithEarned",
    "OnGameTurnStarted",
    "OnGreatPersonActivated",
    "OnNewMajorityReligion",
    "OnPillage",
    "OnUnitRetreated",
    "PlayerTurnStartComplete",
    "PlayerTurnStarted",
}

local numCall = {}
local eventsFunctions = {}

for i, eventName in ipairs(eventslist) do 
    print("Adding Listen to Events." .. eventName)
    numCall[eventName] = 0
    eventsFunctions[eventName] = function (...) if numCall[eventName] < maxCall then print("-- Events."..eventName);    getEventArguments(...);    numCall[eventName] = numCall[eventName] + 1; else Events[eventName].Remove( eventsFunctions[eventName] ) end;    end;
    Events[eventName].RemoveAll() -- remove previous listener when running the code again...
    Events[eventName].Add( eventsFunctions[eventName] )
end

for i, eventName in ipairs(gameEventsList) do
    print("Adding Listen to GameEvents." .. eventName)
    numCall[eventName] = 0
    eventsFunctions[eventName] = function (...) if numCall[eventName] < maxCall then print("-- GameEvents."..eventName);    getEventArguments(...);    numCall[eventName] = numCall[eventName] + 1; else GameEvents[eventName].Remove( eventsFunctions[eventName] ) end;    end;
    GameEvents[eventName].RemoveAll()
    GameEvents[eventName].Add( eventsFunctions[eventName] )
end


Dumps from script and UI contexts attached (as of Spring patch)
 

Attachments

  • dump in script.txt
    24.7 KB · Views: 999
  • dump in UI context.txt
    32.3 KB · Views: 728
Last edited:
How did you find these? I presume it's within the DLL but how did you open it? (I'm a bit of a noob, sorry.)
 
Using this
Code:
function l(object) print("Attributes:") for k, v in pairs(getmetatable(object).__index) do print(k); end; print("End attributes."); end
or this
Code:
function p(table) for k, v in pairs(table) do print(k); end; end
on whatever I found in the Lua files of the game.

need to do units and cities, events, ...

see also: http://forums.civfanatics.com/threads/lua-environment-and-sandboxing.487598/
 
I assume more "Set" type functions will be forthcoming as most seem to be of a "Get" nature.
 
Thanks Gedemon! Do you have any information on the TerrainBuilder class? I want to override the StampContinents method in a map script, and I was hoping I could call something like TerrainBuilder.SetContinent much like TerrainBuilder.SetTerrainType is called. None of the base game scripts do any continent handling on their own, so I'm not sure where to begin.
 
I tried writing an iterative function that would list all elements in _G, and then if that element is a table, list all of that table's elements, and so forth. Upon running it my game crashed.
 
I tried writing an iterative function that would list all elements in _G, and then if that element is a table, list all of that table's elements, and so forth. Upon running it my game crashed.

If it's like 5, then _G is not available to mods.
 
Gedemon, do you have any idea what the arguments for these are?
 
Nice!! How did you do it?

They're all listed in the DLL in the .rdata section (At 0x60dc00). There's more there too, like member variables, all the localisation strings and some database calls, but I cut those out. Here's the full (almost) list: http://pastebin.com/tfjSH37E the section names are wrong though, they're not laid out uniformly and they get out of order Half are right half are wrong, easy to see most of the wrong ones.
 
Last edited:
They're all listed in the DLL in the .rdata section (At 0x60dc00). There's more there too, like member variables, all the localisation strings and some database calls, but I cut those out. Here's the full (almost) list: http://pastebin.com/tfjSH37E the section names are wrong though, they're not laid out uniformly and they get out of order Half are right half are wrong, easy to see most of the wrong ones.
How did you access the DLL?
 
How did you access the DLL?

Hex Workshop. Can also open up the game in a debugger and find all referenced strings if you want to do it that way, but you'll get so much irrelevant stuff that way.

Been trying to look at how to get the arguments, but Lua is so weird I just can't figure it out. Each function has a pushnamedcclosure call with it, with a unique function location, so you'd assume that's it right? Well I tried with GetGold and for something that should be incredibly simple Lua runs through so so much crap. I can't find the gold value anywhere. The location first returned is the goddamn location of the camera to move to when you click the city banner. Just... Why? Can't find the gold, but I can have the camera move to the other side of the map when clicking on a city banner, awsum. >.>

If someone's good with Lua plix explain how this works. TTABLES and TSTRINGS everywhere, but no values.
 
Last edited:
Top Bottom