Lua API documentation [780]

The Lua scripting language allows you to give your plugin more advanced features.

Moderator: Plugin Moderators

User avatar
FranchuFranchu
Inhabitant of a Country
Posts: 799
Joined: 28 May 2017, 00:07
Location: Freezing in Argentina
Plugins: Showcase Store
Version: Beta

Plugin Creator

Platform

Lua API documentation [780]

#1

Post by FranchuFranchu »

Also see doc.theotown.com
Show
Analytics
void function Analytics.log(category, action, label) ["hide"]
Show
Array
void function Array:new(arr)
void function Array.normalize(arr)
void function Array:forEach(callbackFunction) @type Array Iterates over all elements of the array and applieds a function on them. This is especially useful to avoid explicit use of a for loop. However, this functional style comes at an allocation and performance cost because of the function. Use it when it suits your needs.

Code: Select all

local a = Array{1, 2, 3} 
for i = 1, #a do --Typical approach 
print(a[i]) 
end 
a:forEach(function(x) print(x) end) --Functional style 
array function Array:map(mapFunction) Maps all elements to a new array using a given function.

Code: Select all

local a = Array{1, 2, 3} 
local b = a:map(function(x) return 2 * x end) 
print(tostring(b))  --Prints {2, 4, 6} 
array function Array:filter(filterFunction) Creates a copy that only contains filtered elements.

Code: Select all

local a = Array{1, 2, 3} 
local b = a:filter(function(x) return x % 2 == 1 end) --Keep uneven numbers 
print(tostring(b))  --Prints {1, 3} 
number function Array:count(predicate) Counts how many elements fulfill a given predicate. for an element of the array.
bool function Array:exists(predicate) Returns true if at least one element matches the given predicate. for an element of the array.
numbers function Array:add(element, index) Adds an object to the array. An index can be provided to specify a position for insertion. If no index was provided the object will be appended to the array.

Code: Select all

local a = Array() 
a:add(1) 
a:add(2) 
a:add(3, 1) 
print(tostring(a))  --Prints {3, 1, 2} 
numbers function Array:addAll(arr, index) Adds an object to the array. An index can be provided to specify a position for insertion. If no index was provided the elements will be appended to the array.

Code: Select all

local a = Array{1, 2, 3} 
local b = Array{4, 5, 6} 
a:addAll(b, 2) 
print(tostring(a))  --Prints {1, 4, 5, 6, 2, 3} 
number function Array:find(element) Returns the index of an object in the array. If the array doesn't contain it the function returns -1.

Code: Select all

local a = Array{'a', 'b', 'c'} 
print(a:find('b'))  --Prints 2 
bool function Array:contains(element) Returns true if the given object is part of the array.

Code: Select all

local a = Array{'a', 'b', 'c'} 
print(a:contains('b'))  --Prints true 
print(a:contains('d'))  --Prints false 
bool function Array:isEmpty([]) Returns true if the array is empty. This is equivalent to checking the size size of the array being 0 manually.

Code: Select all

local a = Array() 
print(a:isEmpty()) 
a:add(1) 
print(a:isEmpty()) 
void function Array:removeAt(i) Removes the object at a specific index.
bool function Array:remove(element) Removes the first appearance of an object from the array.
void function Array:clear([]) Clears the array by removing all elements. The resulting size of the array will be 0.
void function Array:sort(compFunc) Uses natural order of the elements in the array to sort them. You can optionally provide your own function for comparing two elements. specifying whether the first argument should be before the second argument in the array. The default behaviour is ascending order.

Code: Select all

local arr = Array{1, 5, 0, 6, 1, 3, 2, 4} 
arr:sort() 
print(tostring(arr))  --Prints {0, 1, 1, 2, 3, 4, 5, 6} 
arr:sort(function(a,b) return a > b end) 
print(tostring(arr))  --Prints {6, 5, 4, 3, 2, 1, 1, 0} 
void function Array:shuffle([]) Shuffles the elements of the array into a random order. The function uses _math.random_ internally so that the result is dependent on the current random seed value. To get diferent results for diferent runs you might call >_math.randomseed(os.time())_ at the start of your program.

Code: Select all

local a = Array{0, 1, 2, 3, 4, 5, 6} 
a:shuffle() 
print(tostring(a))  --Prints {5, 3, 4, 1, 6, 2, 0} 
void function Array:pick([]) Returns a random element of the array. Returns **nil** if the array is empty.

Code: Select all

local a = Array{1, 2, 3} 
print(a:pick()) 
array function Array:sub(startIndex, length) Creates a sub-array for the specified range. will be copied to the end.

Code: Select all

local a = Array{1, 2, 3, 4, 5, 6} 
print(tostring(a))  --Prints {1, 2, 3, 4, 5, 6} 
local b = a:sub(2, 4) 
print(tostring(b))  --Prints {2, 3, 4, 5} 
array function Array:copy([]) Returns a copy of the array.

Code: Select all

local a = Array{1, 2, 3} 
local b = a:copy() 
b[1] = 42 
print(tostring(a))  --Prints {1, 2, 3} 
print(tostring(b))  --Prints {42, 2, 3} 
string function Array:join(separator) Joins the contents of the array into a string using the specified separator.
void function mt:__tostring([])
void function Array.fromJavaList(list)
void function Array.fromJavaArray(arr)
Show
Builder
bool function Builder.isBuildingBuildable( draft, x, y) Checks whether the specified building draft can be built at the given position x, y. Returns true if the building can be built.
number function Builder.getBuildingPrice( draft, x, y) Returns the price of the building. May change with time.
bool function Builder.buildBuilding( draft, x, y, frame) Tries to build the given building draft at the specified position and sets it's frame if a frame was specified. Returns true if the build was was successful. was specified a random frame will be used (in case the building has multiple frames).
void function Builder.getBuildingUpgradePrice(draft, x, y)
void function Builder.buildBuildingUpgrade(draft, x, y)
void function Builder.removeBuildingUpgrade(draft, x, y)
bool function Builder.isRoadBuildable(draft draft, x0, y0, x1, y1, level0, level1, bridge) Checks whether the specified road draft can be build along the given line x0,y0 - x1,y1. To build a bridge manually you have to set level0 = level1 and bridge = true Only a single lane will be built so a valid line has to fulfill the property x0 == x1 or y0 == y1 For this option to work _level0_ and _level1_ must be equal. Default is **false**.
number function Builder.getRoadPrice( draft, x0, y0, x1, y1, level0, level1, bridge) Returns the price of the road. May change with time. For this option to work _level0_ and _level1_ must be equal. Default is **false**.
bool function Builder.buildRoad(draft draft, x0, y0, x1, y1, level0, level1, bridge) Tries to build the given road draft along the given line. Returns true if building was successful. For this option to work _level0_ and _level1_ must be equal. Default is **false**.
bool function Builder.isTreeBuildable(draft draft, x, y) Checks whether the specified tree draft can be built at the specified position.
number function Builder.getTreePrice(draft draft, x, y) Returns the price of the tree. May change with time.
bool function Builder.buildTree(draft draft, x, y, frame) Tries to build the given tree draft at the specified position x, y and return true if this was successful. If frame is specified it also tries to set the frame of the tree accordingly. will be picked if it isn't specified.
bool function Builder.isRoadDecoBuildable(draft draft, x, y, level) Returns true if the given road decoration can be applied to the road at the specified location. level.
number function Builder.getRoadDecoPrice(draft draft, x, y, level) Returns the price of the road deco. May change with time. level.
bool function Builder.buildRoadDeco(draft draft, x, y, level) Tries to build the given road decoration draft on the road on the specified location. Returns true if this was successful. level.
bool function Builder.isGroundBuildable(draft draft, x, y) Returns true if the ground draft can be built at the given location. **true** for water or **false** for land. A generic ground draft will be used then.
number function Builder.getGroundPrice(draft draft, x, y) Returns the price of the ground. May change with time. **true** for water or **false** for land. A generic ground draft will be used then.
bool function Builder.buildGround(draft draft, x, y) Builds the specified ground draft and returns true if building was successful. **true** for water or **false** for land. A generic ground draft will be used then.
void function Builder.remove(x, y) Removes anything from the specified location.
void function B:init(_city, _modifier) Attachment
Last edited by FranchuFranchu on 22 Jun 2019, 17:04, edited 2 times in total.

User avatar
FranchuFranchu
Inhabitant of a Country
Posts: 799
Joined: 28 May 2017, 00:07
Location: Freezing in Argentina
Plugins: Showcase Store
Version: Beta

Plugin Creator

Platform

Lua API documentation II [780]

#2

Post by FranchuFranchu »

Show
City
void function City.alert(integer actionPlaceTinteger ype, integer x, integer y)

Code: Select all

---Identifier for fire disaster. Used by City.getDisaster and City.issueDisaster.
City.DISASTER_FIRE = "fire"
---Identifier for meteorite disaster.
City.DISASTER_METEOR = "meteor"
---Identifier for earthquake disaster.
City.DISASTER_EARTHQUAKE = "earthquake"
---Identifier for nuke disaster.
City.DISASTER_NUKE = "nuke"
---Identifier for tornado disaster.
City.DISASTER_TORNADO = "tornado"
---Identifier for illness disaster.
City.DISASTER_ILLNESS = "illness"
---Identifier for flooding disaster.
City.DISASTER_FLOODING = "flooding"
---Identifier for riot disaster.
City.DISASTER_RIOT = "riot"
---Identifier for crime disaster.
City.DISASTER_CRIME = "crime"
---Identifier for ufo disaster.
City.DISASTER_UFO = "ufo"
---Identifier for green slime disaster.
City.DISASTER_GREEN_SLIME = "green slime"
---Identifier for pink slime disaster.
City.DISASTER_PINK_SLIME = "pink slime"
---Identifier for blizzard disaster.
City.DISASTER_BLIZZARD = "blizzard"

---
---Action place for fire alerts. Used for action place markers.
City.ACTIONPLACE_FIRE = 0
---Action place for police alerts.
City.ACTIONPLACE_POLICE = 1
---Action place for medic alerts.
City.ACTIONPLACE_MEDIC = 2
---Action place for swat alerts.
City.ACTIONPLACE_SWAT = 3
---Action place for garbage alerts.
City.ACTIONPLACE_GARBAGE = 4
void function City.getName() return city:getName() Name of the current city
void function City.getFileName() return keeper and keeper:getFile() Returns the name of the file of the city.
void function City.setName(string newName) Sets a new city name
void function City.getRotation() return city:getRotation() Returns the current rotation of the city. City rotation is expressed with an integer number 0 (unrotated), ..., 3
void function City.setRotation(r) Sets the rotation of the city
void function City.getWidth([]) Width of the city in tiles
void function City.getHeight([]) Height of the city in tiles
void function City.getSeed() return city:getSeed() Returns the seed that was used to generate the city
void function City.getAuthor() return city:getAuthor() Returns the name of the author that the player entered
void function City.setAuthor(name) Sets a new author name for the city.
integer function City.getXp() return city:getXp() Returns the amount of xp of the city.
void function City.setXp(xp) Sets the amount of xp of the city.
draft, function City.getRank() local r = city:getRank() Returns the current rank draft and the rank index
bool function City.isSandbox() return city:getGameMode() Determines whether the city is in free or sandbox mode
bool function City.isReadonly() return city:isReadonly() Indicates whether this city is readonly. Cities that are readonly can not be saved. For example foreign cities in online regions are read only.
void function City.getMoney() return _budget:getEstate() Estate of the city
void function City.spendMoney(amount, x, y, budgetItem) Spends some money. If x, y is specified it will show a red price at that location.
void function City.earnMoney(amount, x, y, showOverlay, budgetItem) Earns some money. If x, y is provided (and >= 0) then the money will be drawn as if it was earned at the provided place (green text). If showOverlay is true and overlay for the money will be shown (default is false). Requires privileged rights.
void function City.getCurrency(string name) Returns the available amount of the currency of the given name. E.g. City.getCurreny('bus currency')
void function City.spendCurrency(string name, number amount) Spends amount of the currency named name.
void function City.earnCurrency(string name, number amount) Earns amount of the currency named name. Requires privileged rights.
void function City.getPeople(number optional level) Returns the number of the specified level (0, 1 or 2). Returns the number of all people if no level was specified.
void function City.addPeople(level, amount)
void function City.getStorage([]) Use this storage table to save things city wide
number function City.getFunVar(name, fallbackValue) Returns the value of the classic fun variable of the given name or fallbackValue if no such variable has been defined, yet. fallbackValue is 0 by default. Note that fun variables can only contain numbers. Use City.getStorage() or TheoTown.getStorage() to store more fancy stuff. Global fun variables are indicated by a leading ! in it's name.
void function City.setFunVar(name, value) Sets the value of a classic fun variable called name. Note that fun variables can only contain numbers. Use City.getStorage() or TheoTown.getStorage() to store more fancy stuff. Global fun variables are indicated by a leading ! in it's name.
number function City.getTime() return _date:getAnimationTime() Returns the animation time of the game in milliseconds.
number function City.getAbsoluteDay() return _date:getAbsoluteDay() Returns the current absolute day of the city.
number function City.getDay() return _date:getDay() Returns the current day of the month of the city.
number function City.getMonth() return _date:getMonth() Returns the current month of the city.
number function City.getYear() return _date:getYear() Returns the current year of the city.
number function City.countBuildings(opt draft draft) Returns the overall amount of buildings. Optionally of a specific draft. This can for example be used to iterate over all buildings of a draft by using _City.getBuilding(index, draft)_.
number, function City.getBuilding(index, opt draft draft) Gets the position of a specific building of a specific draft by it's index.
void function City.forEachBuilding(f, draft)
number function City.countRoads(opt draft draft) Returns the overall amount of roads. Optionally of a specific draft. This can for example be used to iterate over all roads (of a draft) by using _City.getRoad(index, draft)_.
number, function City.getRoad(index, opt draft draft) Gets the position and level of a specific road (of a specific draft) by it's index.
void function City.forEachRoad(f, draft)
void function City.spawnCar(carDraft, startX, startY, targetX, targetY, frame) Spawns a car at a given position / position of a building that drives to the given target / building at the target. The car will actually not spawned immediately but after a path has been calculated. This happens asynchronously since path calculation is heavy on computation. You can provide a frame to determine the actualy type of the car. It will be random by default.
void function City.getDisaster([]) Returns the name of the curretly active disaster or nil if no disaster is is active right now.
void function City.issueDisaster(string name, x, y, radius, radioactive) Issues the disaster of the given name at the given position x, y. Returns true if disaster was issued successfully.
void function City.enableDisaster(name, state) Enables or disables the automatic disaster of the given name.
number,number,number function City.getView([]) Returns the tile position the camera is currently looking at as well as the current scale. Format: x, y, scale
void function City.setView(x, y, scale) Sets the view to a specified tile x, y using the provided scale. If no scale is provided the current scale will be used. Scale 1 means no scaling, 2 times scaling etc.
void function City.save(enforce) Saves the city if the user has autosave enabled. If enforce is set the city will even be saved if the user has autosave disabled.
void function City.load(path, overwrite, private, target) Loads a city file provided by the plugin. path is the file of the city file (thus it includes the .city file ending). Prior to loading the city will be copied to maps or private maps folder first (depending on private value). If a city of similar file name already exists at that directory it will be overridden if overwrite flag is set. The target file name can be changed by specifieing a target name.
void function City.exit(save) Closes the current city and will go back to region view.
void function City.getCities([])
void function City.setSpeed(speed) Sets the simulation speed of the city. The following values are allowed: `0` for paused `1` for slow `2` for normal `3` for fast `4` for ultra fast @see City.getSpeed
number function City.getSpeed([]) Returns the current simulation speed of the city. @see City.setSpeed
void function City.hideNotification(id)
void function City.clearNotifications([])
void function City.setBackground(draft draft) Sets a background.
draft function City.getBackground([]) Returns the current background draft of the city.
number function City.getHappiness([]) Returns the average happiness.
number function City.noise(x, y, z, w) Returns a noise value for the specified coordinates.
number function City.getPlayTime([]) Returns the play time in this city in seconds.
true function City.isUber() return city:isUber() Returns true if uber is activated for that city.
number function City.countCars() return _traffic:countCars() Returns number of cars that are active right now. This includes operatonal cars and trains.
void function City.getCity([])
void function C:init(orig, origKeeper) Attachment---
Show
Debug
void function Debug.log(message, ...) Logs a message into the script internal log.
void function Debug.toast(message, ...) Shows the specified message as toast overlay. It's discouraged to call this function too often since new messages are postponsed if a previous message is still displayed.
void function Debug.info(message, ...) Logs a message into the debug overlay of the game. This function is meant to be used within the script:update() method since the log is cleared every frame. Calling this function opens the debug overlay automatically, so ensure to remove it in your production code.

User avatar
FranchuFranchu
Inhabitant of a Country
Posts: 799
Joined: 28 May 2017, 00:07
Location: Freezing in Argentina
Plugins: Showcase Store
Version: Beta

Plugin Creator

Platform

Re: Lua API documentation III [780]

#3

Post by FranchuFranchu »

Show
Draft
draft function Draft.getDraft(id) Returns the draft of the given id. **nil** is returned if no draft of the given id was found.
array function Draft.getDrafts(tag) Returns an array of drafts that have the given tag defined. If no tag is provided this function returns a list of all available drafts.
void function Draft.callAll(name, arg1, ...) Calls the event function called *name* on all scripts if defined.
string function Draft:getId([]) This type represents drafts. @type Draft Returns the id of the draft.
string function Draft:getTitle([]) Returns the localized title of the draft.
string function Draft:getText([]) Returns the localized description of the draft.
string function Draft:getAuthor([]) Returns the author of the draft as defined in it's definition.
string function Draft:getType([]) Returns a string that represents the concrete type of the draft.
bool function Draft:isBuilding([]) Returns **true** if the draft defines a building.
bool function Draft:isRCI() return self.orig.buildingType ~= nil and self.orig.buildingType:isRCI() Returns **true** if the draft defines a building that is either residential, commercial or industrial.
bool function Draft:isResidential() return self:getType() Returns **true** if the draft defines a residential building.
bool function Draft:isCommercial() return self:getType() Returns **true** if the draft defines a commercial building.
bool function Draft:isIndustrial() return self:getType() Returns **true** if the draft defines a industrial building.
bool function Draft:isRoad() return self:getType() Returns **true** if the draft defines a road.
bool function Draft:isRoadDecoration() return self:getType() Returns **true** if the draft defines a road decoration.
bool function Draft:isAnimation() return self:getType() Returns **true** if the draft defines a building.
bool function Draft:isGround() return self:getType() Returns **true** if the draft defines a ground type.
bool function Draft:isCar() return self:getType() Returns **true** if the draft defines a car.
bool function Draft:isTree() return self:getType() Returns **true** if the draft defines a tree.
bool function Draft:isTemplate() return self:getType() Returns **true** if the draft defines a draft template.
bool function Draft:isCategory() return self:getType() Returns **true** if the draft defines a category.
number function Draft:getFrameCount([]) Returns the number of frames defined in that draft. Only available for draft types that use frames (e.g. buildings, roads and cars).
number function Draft:getFrame(i) Returns a frame specified by it's index (starting with 1).
void function Draft:setFrame(i, f) Overrides a frame by index. Starting index is 1.
number function Draft:getPrice([]) Returns the price defined for this draft. Not all draft types support to have a price.
number function Draft:getMonthlyPrice([]) Returns the monthly price defined for this draft. Not all draft types support to have a monthly price.
number function Draft:getWidth([]) Returns the width of the building. Only available for building drafts.
number function Draft:getHeight([]) Returns the height of the building. Only available for building drafts.
void function Draft:setVisible(state) Sets the visibility state of the draft. For buildings the visibility state defined whether they are present in the toolbar.
bool function Draft:isVisible([]) Returns **true** if the draft is visible.
table function Draft:getMeta() return self.orig:getLuaMeta() Returns the meta table of the draft if available. nil otherwise.
table function Draft:getContent() return self.orig:getLuaContent() For template and data drafts only: returns the raw json definition of the draft.
array function Draft:getScripts([]) Returns an array of all attached scripts to this draft. Don't modify the returned array.
void function Draft:call(name, args) Calls the event function called *name* on all scripts of the draft if defined.
void function Draft:__tostring([])
void function D:new(orig) Attachment--
void function D:init([])
Show
Drawing
void function Drawing.getSize([]) Returns the current screen size width, height in pixels. Note that the result may change over time due to resolution changes.
void function Drawing.setScale(sx, sy)
void function Drawing.getScale([])
void function Drawing.setTile(tileX, tileY, offsetX, offsetY)
void function Drawing.reset([])
void function Drawing.setColor(r, g, b)
void function Drawing.getColor([])
void function Drawing.setAlpha(alpha)
void function Drawing.getAlpha([])
void function Drawing.getTextSize(text, font)
void function Drawing.getImageSize(frame)
void function Drawing.drawText(text, x, y, font)
void function Drawing.drawImage(frame, x, y)
void function Drawing.drawImageRect(frame, x, y, w, h)
void function Drawing.drawLine(x0, y0, x1, y1, width)
void function Drawing.drawTileImage(frame)
Show
GUI
gadget function GUI.getMaster([]) Returns the root gui object.
gadget function GUI.find(id) Finds a gadget by it's id.
void function G._init(m) Attachment--
Show
Runtime
string function Runtime.getName([]) Name of the application, should be 'TheoTown'
string function Runtime.getVersion([]) Current version of TheoTown, e.g. 1.5.15
number function Runtime.getVersionCode([]) Current version of TheoTown as number, e.g. 515
string function Runtime.getId([]) Package id of the app, should be 'info.flowersoft.theotown.theotown'
number,string function Runtime.getOSVersion([]) Returns the version code of the os (e.g. Android API level).
string function Runtime.getPlatform([]) Returns a string that represents that platform TheoTown is running on right now. E.g. 'android', 'ios' or 'desktop'.
bool function Runtime.isPremium([]) Returns true if this copy of TheoTown is a premium version.
string,string function Runtime.getModel([]) Returns model name and manufacturer of the device.
bool function Runtime.isDebug([]) Returns a bool.
number function Runtime.getTime([]) Unix timestamp in milliseconds
table function Runtime.fromJson(json) Converts a json string into a lua table.
string function Runtime.toJson(tbl) Converts a table into a json string.
string function Runtime.getUuid([]) Returns a random uuid string.
void function Runtime.getStage([])
void function Runtime.getStageName([])
void function Runtime.pushStage([])
void function Runtime.popStage([])
void function Runtime.postpone(foo, delayMS) Postpones the execution of a function. Postponed functions will be executed synchronously once per frame. You can optionally set a minimum time to wait until execution. until execution.
void function Runtime.setClipboard(text)
Last edited by FranchuFranchu on 22 Jun 2019, 17:25, edited 1 time in total.

User avatar
FranchuFranchu
Inhabitant of a Country
Posts: 799
Joined: 28 May 2017, 00:07
Location: Freezing in Argentina
Plugins: Showcase Store
Version: Beta

Plugin Creator

Platform

Re: Lua API documentation IV [780]

#4

Post by FranchuFranchu »

Show
Script

Code: Select all

---
--Event types
--@section

---
--Will be called for building and road drafts right after placement.
--@see script:event
Script.EVENT_PLACED = 0;

---
--Will be called for building and road drafts right after construction.
--That is immediately after placements for roads and for buildings witht zero
--buildtime.
Script.EVENT_FINISHED = 1

---
--Will be called for building with car spawner whenever a car was spawned.
Script.EVENT_CAR_SPAWNED = 2

---
--Will be called for building with car spawner whenever a car reached it's
--target.
Script.EVENT_CAR_REACHED = 3

---
---Will be called for building with car spawner whenever a car was despawned.
Script.EVENT_CAR_DESPAWNED = 4

---
--Will be called for scripts attached to a generic tool when users selects
--the tool.
Script.EVENT_TOOL_ENTER = 5

---
--Will be called for scripts attached to a building before it gets removed.
Script.EVENT_REMOVE = 6

---
--Will be called for scripts attached to a building after an upgarde of it
--was finished.
Script.EVENT_UPGRADE = 7
void function script:init([])
void function script:update([])
script function Script.getScript([]) Returns the current script or **nil** if no script is running right now. Since scripts are executed synchronously to avoid race conditions there can only be one script running.
array function Script.getScripts(tag) Returns an array of all scripts, or, if tag is specified, an array of all scripts that defined the given tag. Don't manipulate the returned array directly.
number function Script:getId([]) Here you see the methods that a script object offers. @type Script Every script is uniquely identified by a single number. Note that this identifier is only constant during runtime. It may be diferent in the next session, therefore you shouldn't rely on it.
draft function Script:getDraft([]) Returns the draft the script is attached to. Every script instance is attached to exactly one draft. However, multiple instances of the same script may be attached to diferent drafts.
string function Script:getName([]) Returns the name of the script. E.g. the name of a script >folder/test.lua is just `test`.
string function Script:getPath([]) Returns the relative path of the script.
string function Script:getLocation([]) Returns a readable location identifier that contains the draft id.
array function Script:getParents([]) Returns an array of all parent scripts.
script function Script:getParent([]) Returns the parent script if there is any, **nil** otherwise. A parent script is the script that instantiated this script using `script:addScript()` Scripts are usually not instantiated by other scripts.
void function Script:setActive(state) Activates or disables the script. No event methods will be called on disabled scripts. A disabled script cannot re-enable itself since it won't be updated anymore.
bool function Script:isActive([]) Determines whether the script is active right now.
void function Script:addTag(tag) Adds a tag to this script. Tags can be used to find scripts by using `getScripts(tag)`.
array function Script:getTags([]) Returns an array that contains the tags that have been defined for that script.
script function Script:addScript(name, draft, initializer) Adds a script to a draft. Only call this method in the init or lateInit methods to ensure that it will be executed correctly. However, init and/or lateInit might not be called on the new script automatically. Format of initializer: initializer(script) If no initializer is provided the own initializer will be used. Returns the newly created script.
void function script:earlyInit([]) Event functions @section Will be called on all scripts before script:init(). Use this method to set up early things.
void function script:init([]) Will be called once after all drafts and scripts have been loaded.
void function script:lateInit([]) Will be called once after script:init() has been called on all scripts. Use this method for things that relay on other scripts' setup.
void function script:isBuildable(number x, number y, number level) For buildings and roads only: Will be queried to determine if a building/road can be built at a specific location. To prevent buildability just let it return false. Is also queried for custom tools to determine buildability.
void function script:daily(number x, number y, number level) Will be called on a daily basis for every building or road that are instances of the owning draft. Level is 0 for buildings.
void function script:click(number x, number y, number level) Will be called when the user taps on a building or road that is an instance of the owning draft. Level is 0 for buildings.
void function script:event(x, y, level, event) Will be called for building/road/tool events of instances of the owning draft. Level is 0 for buildings. @see Script.EVENT_PLACED
void function script:draw(x, y, level) Will be called after a building/road instance has been drawn. Will also be called on all visible tiles for custom tools.
void function script:random(x, y) Will be called every day for scripts whose owning draft is a building or road. x and y is a random (valid) postion on the map.
void function script:nextDay([]) Will be called on a daily basis for each script.
void function script:nextMonth([]) Will be called on a monthly basis for each script.
void function script:nextYear([]) Will be called on a yearly basis for each script.
void function script:update([]) Will be called per frame for each script while a city is open. Can be used to draw stuff on the screen (under the UI). Use overlay() do draw on top of UI and/or outside of cities.
void function script:click(x, y) Will be called when users taps on a building/road of this draft while being in default tool. Return false to prevent opening the default tile dialog. You should favor this method over earlyTap() and tap() as they operate indepently of tile dialog and selected tool and don't take the own draft into consideration. This method will also be called for custom tools if user taps on a tile and script:isBuildable() returned true for it.
void function script:earlyTap(tileX,tileY,x,y) Will be called when the user taps on the map. Will be called just before the tap is handled by the current tool.
void function script:tap(tileX,tileY,x,y) Will be called when the user taps on the map. Will be called just after the tap is handled by the current tool.
void function script:enterCity([]) Will be called when the user enters a city.
void function script:leaveCity([]) Will be called when the user leaves the city. Don't rely on this method to permanently save state since there's no guarantee that this method will be called.
void function script:enterCityGeneration(phase) Will be called right before a new city is generated.
void function script:leaveCityGeneration(phase) Will be called after city generation process was completed.
void function script:save([]) Will be called just before the city is saved.
void function script:enable([]) Will be called when this script is about to be enabled. Scripts are enabled by definiton right after their creation so this method won't be called then.
void function script:disable([]) Will be called when this script is about to be disabled.
void function script:overlay([]) Will be called once per frame after UI has been drawn. Will also be called outside of cities.
void function script:enterStage([]) Will be called whenever the user enters a stage. A stage is for example a city, the settings screen or the gallery.
void function script:leaveStage([]) Will be called whenever the user leaves a stage. A stage is for example a city, the settings screen or the gallery.
void function S:new(name, path, draft, orig, parent) Attachment--
void function S:__tostring([])
void function S:baseInit([])
Show
TheoTown
number function TheoTown.getGlobalFunVar(name, fallbackValue) Returns the value of the global fun variable of the given name or fallbackValue if no such variable has been defined, yet. fallbackValue is 0 by default. Note that fun variables can only contain numbers. Use City.getStorage() or TheoTown.getStorage() to store more fancy stuff. Global fun variables are indicated by a leading ! in their name.
void function TheoTown.setGlobalFunVar(name, value) Sets the value of a global fun variable called name. Note that fun variables can only contain numbers. Use City.getStorage() or TheoTown.getStorage() to store more fancy stuff. Global fun variables are indicated by a leading ! in their name.
number function TheoTown.getDiamonds([]) Returns the number of diamonds that the user currently has.
void function TheoTown.spendDiamonds(amount) Spends amount diamonds if possible. Returns true if spending was successful, false otherwise.
table function TheoTown.getStorage([]) Returns a game wide storage table. Use it to save data permanently accross all cities.
table function TheoTown.getFileStorage([]) Returns a game wide storage table that's backed by an actual file. The file will even persist if the user deleted the game. Only a deletion of the TheoTown folder will reset this storage.
void function TheoTown.registerCommand(name, f) Registers a function that can then by called from console. Usage: TheoTown.registerCommand('test', function(name, arg) return arg end) Instead of a name you can provide a function that returns true for commands the second function should handle.
void function TheoTown.getExperiment(name)
void function TheoTown.setExperiment(name, value)
void function TheoTown.translate(id)
void function TheoTown.playSound(id, volume) Plays a sound.
void function TheoTown.getId([])
void function TheoTown.getConfig(name)
number function TheoTown.getPlayTime([]) Returns the play time in the game in seconds.
bool function TheoTown.isMultiplayer([]) Returns true if this version of the game is capable of running multiplayer games.
void function isfunction(f)
void function isnumber(n)
void function isstring(s)
void function istable(t)
void function isnil(n)
void function isbool(b)
void function math.randomrange(l, u)
void function math.map(v, vl, vu, l, u)
void function math.lin(v, l, u)
void function string:split(sep)

User avatar
Imran M
Inhabitant of a Country
Posts: 844
Joined: 24 Oct 2018, 13:41
Plugins: Showcase Store

Plugin Creator

Platform

Re: Lua API documentation [550]

#5

Post by Imran M »

In scratch, there's two blocks: broadcast message and when I receive message. Is there anything like that lua?

User avatar
FranchuFranchu
Inhabitant of a Country
Posts: 799
Joined: 28 May 2017, 00:07
Location: Freezing in Argentina
Plugins: Showcase Store
Version: Beta

Plugin Creator

Platform

Re: Lua API documentation [550]

#6

Post by FranchuFranchu »

You can set a fun variable to nil at the start of the program, and then check every tick if it is not nil.
Setup

Code: Select all

function script:init()
     City.setFunVar("banana",nil)
end
To broadcast

Code: Select all

City.setFunVar("banana",42)
To receive

Code: Select all

function script:update()
     if City.getFunVar("banana",nil) ~= nil do
             --what to do when received
     end
end
Its probably very slow tho

User avatar
Lobby
Developer
Posts: 3714
Joined: 26 Oct 2008, 12:34
Plugins: Showcase Store
Version: Beta

Platform

Re: Lua API documentation [550]

#7

Post by Lobby »

In Lua there's a global namespace. So if you put something into a global variable you can read it from anywhere:

Code: Select all

globalvar = 42

function script:update()
  Debug.info('It has value ' .. globalvar)
end
If you use a public Array (TheoTown's replacement for Lists) you can enqueue and dequeue things from it.

However, the most easy thing would be to just call functions on the target script. In this context I'm not sure what the broadcast thing is doing.

User avatar
Imran M
Inhabitant of a Country
Posts: 844
Joined: 24 Oct 2018, 13:41
Plugins: Showcase Store

Plugin Creator

Platform

Re: Lua API documentation [741]

#8

Post by Imran M »

"isBuildingFullOfDeadPeople"
Wow, that's a bit dark.

Post Reply Previous topicNext topic

Return to “Lua Scripting”