mirror of
https://github.com/Bubberstation/Bubberstation.git
synced 2026-08-29 08:08:49 +01:00
Replaces Auxlua with the byondapi-based Dreamluau (#84810)
## About The Pull Request Ever since byondapi went stable, I've been meaning to create a replacement lua library that uses it instead of the auxtools-based auxlua. After so many months, I've finally got the code just about into a position where it's ready for a PR. [Click here](https://hackmd.io/@aloZJicNQrmfYgykhfFwAQ/BySAS18u0) for a guide to rewriting auxlua scripts for dreamluau syntax. ## Why It's Good For The Game Code that runs on production servers should not depend on memory hacks that are liable to break any time Dream Daemon updates. ## Changelog 🆑 admin: Admin lua scripting uses a new library that (probably) will not break when BYOND updates. /🆑 ## TODO: - [x] Convert the lua editor ui to TS - [x] Include a guide for converting scripts from auxlua syntax to dreamluau syntax
This commit is contained in:
@@ -1,150 +1,225 @@
|
||||
# Auxlua
|
||||
# Objects
|
||||
|
||||
---
|
||||
Datums, lists, typepaths, static appearances, and some other objects are represented in Luau as userdata. Certain operations can be performed on these types of objects.
|
||||
|
||||
## Datums
|
||||
## Common metamethods
|
||||
|
||||
DM datums are treated as lua userdata, and can be stored in fields. Due to fundamental limitations in lua, userdata is inherently truthy. Since datum userdata can correspond to a deleted datum, which would evaluate to `null` in DM, the function [`datum:is_null()`](#datumisnull) is provided to offer a truthiness test consistent with DM.
|
||||
The following metamethods are defined for all objects.
|
||||
|
||||
Keep in mind that BYOND can't see that a datum is referenced in a lua field, and will garbage collect it if it is not referenced anywhere in DM.
|
||||
### \_\_tostring(): string
|
||||
|
||||
### datum:get_var(var)
|
||||
Returns the string representation of the object. This uses BYOND's internal string conversion function.
|
||||
|
||||
Equivalent to DM's `datum.var`
|
||||
### \_\_eq(other: any): boolean
|
||||
|
||||
### datum:set_var(var, value)
|
||||
Compare the equality of two objects. While passing the same object into luau twice will return two references to the same userdata, some DM projects may override the equality operator using an `__operator==` proc definition.
|
||||
|
||||
Equivalent to DM's `datum.var = value`
|
||||
## Datum-like Objects
|
||||
|
||||
### datum:call_proc(procName, ...)
|
||||
Datum-like objects include datums themselves, clients (if they have not been redefined to be children of `/datum`), static appearances, and the world.
|
||||
|
||||
Equivalent to DM's `datum.procName(...)`
|
||||
### \_\_index(index: string): any
|
||||
|
||||
### datum:is_null()
|
||||
Access the member specified by `index`.
|
||||
|
||||
This function is used to evaluate the truthiness of a DM var. The lua statement `if datum:is_null() then` is equivalent to the DM statement `if(datum)`.
|
||||
If `index` is a valid var for the object, the index operation will return that var's value.
|
||||
If the var getting wrapper proc is set, the operation will instead call that proc with the arguments `(object, index)`.
|
||||
|
||||
### datum.vars
|
||||
For objects other than static appearances, if `index` is a valid proc for the object, the operation will return a wrapper for that proc that can be invoked using call syntax (e.g. `object:proc(...arguments)`). If the object proc calling wrapper is set, calling the returned function will instead call the wrapper proc with the arguments `(object, proc, {...arguments})`. Note that vars will be shadowed by procs with the same name. To work around this, use the `dm.get_var` function.
|
||||
|
||||
Returns a userdatum that allows you to access and modifiy the vars of a DM datum by index. `datum.vars.foo` is equivalent to `datum:get_var("foo")`, while `datum.vars.foo = bar` is equivalent to `datum:set_var("foo", bar)`
|
||||
### \_\_newindex(index: string, value: any): ()
|
||||
|
||||
---
|
||||
Set the var specified by `index` to `value`, if that var exists on the object.
|
||||
|
||||
If the var setting wrapper proc is set, the operation will instead call that proc with the arguments `(object, index, value)`.
|
||||
|
||||
## Lists
|
||||
|
||||
In order to allow lists to be modified in-place across the DM-to-lua language barrier, lists are treated as userdata. Whenever running code that expects a DM value, auxlua will attempt to convert tables into lists.
|
||||
Lists are syntactically similar to tables, with one crucial difference.
|
||||
Unlike tables, numeric indices must be non-zero integers within the bounds of the list.
|
||||
|
||||
List references are subject to the same limitations as datum userdata, but you are less likely to encounter these limitations for regular lists.
|
||||
### \_\_index(index: any): any
|
||||
|
||||
Some lists (`vars`, `contents`, `overlays`, `underlays`, `vis_contents`, and `vis_locs`) are inherently attached to datums, and as such, their corresponding userdata contains a weak reference to the containing datum. Use [`list:is_null`](#listisnull) to validate these types of lists.
|
||||
Read the list at `index`. This works both for numeric indices and assoc keys.
|
||||
Vars lists cannot be directly read this way if the var getting wrapper proc is set.
|
||||
|
||||
### list.len
|
||||
### \_\_newindex(index: any, value: any): any
|
||||
|
||||
Equivalent to DM's `list.len`
|
||||
Write `value` to the list at `index`. This works both for writing numeric indices and assoc keys.
|
||||
Vars lists cannot be directly written this way if the var setting wrapper proc is set.
|
||||
|
||||
### list:get(index)
|
||||
### \_\_len(): integer
|
||||
|
||||
Equivalent to DM's `list[index]`
|
||||
Returns the length of the list, similarly to the `length` builtin in DM.
|
||||
|
||||
### list:set(index, value)
|
||||
### Iteration
|
||||
|
||||
Equivalent to DM's `list[index] = value`
|
||||
Lists support Luau's generalized iteration. Iteration this way returns pairs of numeric indices and list values.
|
||||
For example, the statement `for _, v in L do` is logically equivalent to the DM statement `for(var/v in L)`.
|
||||
|
||||
### list:add(value)
|
||||
# Global Fields and Modules
|
||||
|
||||
Equivalent to DM's `list.Add(value)`
|
||||
In addition to the full extent of Luau's standard library modules, some extra functions and modules have been added.
|
||||
|
||||
### list:remove(value)
|
||||
## Global-Level Fields
|
||||
|
||||
Equivalent to DM's `list.Remove(value)`
|
||||
### sleep(): ()
|
||||
|
||||
### list:to_table()
|
||||
Yields the active thread, without worrying about passing data into or out of the state.
|
||||
|
||||
Converts a DM list into a lua table.
|
||||
Threads yielded this way are placed at the end of a queue. Call the `awaken` hook function from DM to execute the thread at the front of the queue.
|
||||
|
||||
### list:of_type(type_path)
|
||||
### loadstring(code: string): function
|
||||
|
||||
Will extract only values of type `type_path`.
|
||||
Luau does not inherently include the `loadstring` function common to a number of other versions of lua. This is an effective reimplementation of `loadstring`.
|
||||
|
||||
### list:is_null()
|
||||
### print(...any): ()
|
||||
|
||||
A similar truthiness test to [`datum:is_null()`](#datumisnull). This function only has the possibility of returning `false` for lists that are inherently attached to a datum (`vars`, `contents`, `overlays`, `underlays`, `vis_contents`, and `vis_locs`).
|
||||
Calls the print wrapper with the passed in arguments.
|
||||
Raises an error if no print wrapper is set, as that means there is nothing to print with.
|
||||
|
||||
### list.entries
|
||||
### \_state_id: integer
|
||||
|
||||
Returns a userdatum that allows you to access and modifiy the entries of the list by index. `list.entries.foo` is equivalent to `list:get("foo")`, while `list.entries.foo = bar` is equivalent to `list:set("foo", bar)`
|
||||
The handle to the underlying luau state in the dreamluau binary.
|
||||
|
||||
---
|
||||
## \_exec
|
||||
|
||||
## The dm table
|
||||
The `_exec` module includes volatile fields related to the current execution context.
|
||||
|
||||
The `dm` table consists of the basic hooks into the DM language.
|
||||
### \_next_yield_index: integer
|
||||
|
||||
### dm.state_id
|
||||
When yielding a thread with `coroutine.yield`, it will be inserted into an internal table at the first open integer index.
|
||||
This field corresponds to that first open integer index.
|
||||
|
||||
The address of the lua state in memory. This is a copy of the internal value used by auxlua to locate the lua state in a global hash map. `state_id` is a registry value that is indirectly obtained using the `dm` table's `__index` metamethod.
|
||||
### \_limit: integer?
|
||||
|
||||
### dm.global_proc(proc, ...)
|
||||
Calls the global proc `/proc/[proc]` with `...` as its arguments.
|
||||
If set, the execution limit, rounded to the nearest millisecond.
|
||||
|
||||
### dm.world
|
||||
A reference to DM's `world`, in the form of datum userdata. This reference is always valid, since `world` always exists.
|
||||
### \_time: integer
|
||||
|
||||
Due to limitations inherent in the wrapper functions used on tgstation, `world:set_var` and `world:call_proc` will raise an error.
|
||||
The length of successive time luau code has been executed, including recursive calls to DM and back into luau, rounded to the nearest millisecond.
|
||||
|
||||
### dm.global_vars
|
||||
A reference to DM's `global`, in the form of datum userdata. Subject to the same limitations as `dm.world`
|
||||
## dm
|
||||
|
||||
### dm.usr
|
||||
A weak reference to DM's `usr`. As a rule of thumb, this is a reference to the mob of the client who triggered the chain of procs leading to the execution of Lua code. The following is a list of what `usr` is for the most common ways of executing Lua code:
|
||||
- For resumes and awakens, which are generally executed by the MC, `usr` is (most likely) null.
|
||||
- `SS13.wait` queues a resume, which gets executed by the MC. Therefore, `usr` is null after `SS13.wait` finishes.
|
||||
- For chunk loads, `usr` is generally the current mob of the admin that loaded that chunk.
|
||||
- For function calls done from the Lua editor, `usr` is the current mob of the admin calling the function.
|
||||
- `SS13.register_signal` creates a `/datum/callback` that gets executed by the `SEND_SIGNAL` macro for the corresponding signal. As such, `usr` is the mob that triggered the chain of procs leading to the invocation of `SEND_SIGNAL`.
|
||||
The `dm` module includes fields and functions for basic interaction with DM.
|
||||
|
||||
---
|
||||
### world: userdata
|
||||
|
||||
## Execution Limit
|
||||
A static reference to the DM `world`.
|
||||
|
||||
In order to prevent freezing the server with infinite loops, auxlua enforces an execution limit, defaulting to 100ms. When a single lua state has been executing for longer than this limit, it will eventually stop and produce an error.
|
||||
### global_vars: userdata
|
||||
|
||||
To avoid exceeding the execution limit, call `sleep()` or `coroutine.yield()` before the execution limit is reached.
|
||||
A static reference that functions like the DM keyword `global`. This can be indexed to read/write global vars.
|
||||
|
||||
### over_exec_usage(fraction = 0.95)
|
||||
### global_procs: table
|
||||
|
||||
This function returns whether the current run of the Lua VM has executed for longer than the specified fraction of the execution limit. You can use this function to branch to a call to `sleep()` or `coroutine.yield()` to maximize the amount of work done in a single run of the Lua VM. If nil, `fraction` will default to 0.95, otherwise, it will be clamped to the range \[0, 1\].
|
||||
A table that can be indexed by string for functions that wrap global procs.
|
||||
|
||||
---
|
||||
Due to BYOND limitations, attempting to index an invalid proc returns a function logically equivalent to a no-op.
|
||||
|
||||
## Task management
|
||||
The Lua Scripting subsystem manages the execution of tasks for each Lua state. A single fire of the subsystem behaves as follows:
|
||||
- All tasks that slept since the last fire are resumed in the order they slept.
|
||||
- For each queued resume, the corresponding task is resumed.
|
||||
### get_var(object: userdata, var: string): function
|
||||
|
||||
### sleep()
|
||||
Yields the current thread, scheduling it to be resumed during the next fire of SSlua. Use this function to prevent your Lua code from exceeding its allowed execution duration. Under the hood, `sleep` performs the following:
|
||||
Reads the var `var` on `object`. This function can be used to get vars that are shadowed by procs declared with the same name.
|
||||
|
||||
- Sets the [`sleep_flag`](#sleep_flag)
|
||||
- Calls `coroutine.yield()`
|
||||
- Clears the sleep flag when determining whether the task slept or yielded
|
||||
- Ignores the return values of `coroutine.yield()` once resumed
|
||||
### new(path: string, ...any): userdata
|
||||
|
||||
---
|
||||
Creates an instance of the object specified by `path`, with `...` as its arguments.
|
||||
If the "new" wrapper is set, that proc will be called instead, with the arguments `(path, {...})`.
|
||||
|
||||
## The SS13 package
|
||||
### is_valid_ref(ref: any): boolean
|
||||
|
||||
Returns true if the value passed in corresponds to a valid reference-counted DM object.
|
||||
|
||||
### usr: userdata?
|
||||
|
||||
Corresponds to the DM var `usr`.
|
||||
|
||||
## list
|
||||
|
||||
The `list` module contains wrappers for the builtin list procs, along with several other utility functions for working with lists.
|
||||
|
||||
### add(list: userdata, ...any): ()
|
||||
|
||||
Logically equivalent to the DM statement `list.Add(...)`.
|
||||
|
||||
### copy(list: userdata, start?: integer, end?: integer): userdata
|
||||
|
||||
Logically equivalent to the DM statement `list.Copy(start, end)`.
|
||||
|
||||
### cut(list: userdata, start?: integer, end?: integer): userdata
|
||||
|
||||
Logically equivalent to the DM statement `list.Cut(start, end)`.
|
||||
|
||||
### find(list: userdata, item: any, start?: integer, end?: integer): integer
|
||||
|
||||
Logically equivalent to the DM statement `list.Find(item, start, end)`.
|
||||
|
||||
### insert(list: userdata, index: integer, ...any): integer
|
||||
|
||||
Logically equivalent to the DM statement `list.Insert(item, ...)`.
|
||||
|
||||
### join(list: userdata, glue: string, start?: integer, end?: integer): string
|
||||
|
||||
Logically equivalent to the statement `list.Join(glue, start, end)`.
|
||||
|
||||
### remove(list: userdata, ...any): integer
|
||||
|
||||
Logically equivalent to the DM statement `list.Remove(...)`.
|
||||
|
||||
### remove_all(list: userdata, ...any): integer
|
||||
|
||||
Logically equivalent to the DM statement `list.RemoveAll(...)`.
|
||||
|
||||
### splice(list: userdata, start?: integer, end?: integer, ...any): ()
|
||||
|
||||
Logically equivalent to the DM statement `list.Splice(start, end, ...)`.
|
||||
|
||||
### swap(list: userdata, index_1: integer, index_2: integer): ()
|
||||
|
||||
Logically equivalent to the DM statement `list.Swap(index_1, index_2)`.
|
||||
|
||||
### to_table(list: userdata, deep?: boolean): table
|
||||
|
||||
Creates a table that is a copy of `list`. If `deep` is true, `to_table` will be called on any lists inside that list.
|
||||
|
||||
### from_table(table: table): userdata
|
||||
|
||||
Creates a list that is a copy of `table`. This is not strictly necessary, as tables are automatically converted to lists when passed back into DM, using the same internal logic as `from_table`.
|
||||
|
||||
### filter(list: userdata, path: string): userdata
|
||||
|
||||
Returns a copy of `list`, containing only elements that are objects descended from `path`.
|
||||
|
||||
## pointer
|
||||
|
||||
The `pointer` module contains utility functions for interacting with pointers.
|
||||
Keep in mind that passing DM pointers into luau and manipulating them in this way can bypass wrapper procs.
|
||||
|
||||
### read(pointer: userdata): any
|
||||
|
||||
Gets the underlying data the pointer references.
|
||||
|
||||
### write(pointer: userdata, value: any): ()
|
||||
|
||||
Writes `value` to the underlying data the pointer references.
|
||||
|
||||
### unwrap(possible_pointer: any): any
|
||||
|
||||
If `possible_pointer` is a pointer, reads it. Otherwise, it is returned as-is.
|
||||
|
||||
# The SS13 package
|
||||
The `SS13` package contains various helper functions that use code specific to tgstation.
|
||||
|
||||
### SS13.state
|
||||
## SS13.state
|
||||
A reference to the state datum (`/datum/lua_state`) handling this Lua state.
|
||||
|
||||
### SS13.get_runner_ckey()
|
||||
## SS13.get_runner_ckey()
|
||||
The ckey of the user who ran the lua script in the current context. Can be unreliable if accessed after sleeping.
|
||||
|
||||
### SS13.get_runner_client()
|
||||
## SS13.get_runner_client()
|
||||
Returns the client of the user who ran the lua script in the current context. Can be unreliable if accessed after sleeping.
|
||||
|
||||
### SS13.global_proc
|
||||
## SS13.global_proc
|
||||
A wrapper for the magic string used to tell `WrapAdminProcCall` to call a global proc.
|
||||
For instance, `/datum/callback` must be instantiated with `SS13.global_proc` as its first argument to specify that it will be invoking a global proc.
|
||||
The following example declares a callback which will execute the global proc `to_chat`:
|
||||
@@ -152,25 +227,18 @@ The following example declares a callback which will execute the global proc `to
|
||||
local callback = SS13.new("/datum/callback", SS13.global_proc, "to_chat", dm.world, "Hello World")
|
||||
```
|
||||
|
||||
### SS13.istype(thing, type)
|
||||
## SS13.istype(thing, type)
|
||||
Equivalent to the DM statement `istype(thing, text2path(type))`.
|
||||
|
||||
### SS13.new(type, ...)
|
||||
Instantiates a datum of type `type` with `...` as the arguments passed to `/proc/_new`
|
||||
The following example spawns a singularity at the caller's current turf:
|
||||
```lua
|
||||
SS13.new("/obj/singularity", dm.global_proc("_get_step", dm.usr, 0))
|
||||
```
|
||||
## SS13.new(type, ...)
|
||||
An alias for `dm.new`
|
||||
|
||||
### SS13.new_untracked(type, ...)
|
||||
Works exactly like SS13.new but it does not store the value to the lua state's `references` list variable. This means that the variable could end up deleted if nothing holds a reference to it.
|
||||
|
||||
### SS13.is_valid(datum)
|
||||
## SS13.is_valid(datum)
|
||||
Can be used to determine if the datum passed is not nil, not undefined and not qdel'd all in one. A helper function that allows you to check the validity from only one function.
|
||||
Example usage:
|
||||
```lua
|
||||
local datum = SS13.new("/datum")
|
||||
dm.global_proc("qdel", datum)
|
||||
dm.global_procs.qdel(datum)
|
||||
print(SS13.is_valid(datum)) -- false
|
||||
|
||||
local null = nil
|
||||
@@ -180,13 +248,13 @@ local datum = SS13.new("/datum")
|
||||
print(SS13.is_valid(datum)) -- true
|
||||
```
|
||||
|
||||
### SS13.type(string)
|
||||
Converts a string into a type. Equivalent to doing `dm.global_proc("_text2path", "/path/to/type")`
|
||||
## SS13.type(string)
|
||||
Converts a string into a typepath. Equivalent to doing `dm.global_proc("_text2path", "/path/to/type")`
|
||||
|
||||
### SS13.qdel(datum)
|
||||
## SS13.qdel(datum)
|
||||
Deletes a datum. You shouldn't try to reference it after calling this function. Equivalent to doing `dm.global_proc("qdel", datum)`
|
||||
|
||||
### SS13.await(thing_to_call, proc_to_call, ...)
|
||||
## SS13.await(thing_to_call, proc_to_call, ...)
|
||||
Calls `proc_to_call` on `thing_to_call`, with `...` as its arguments, and sleeps until that proc returns.
|
||||
Returns two return values - the first is the return value of the proc, and the second is the message of any runtime exception thrown by the called proc.
|
||||
The following example calls and awaits the return of `poll_ghost_candidates`:
|
||||
@@ -194,59 +262,59 @@ The following example calls and awaits the return of `poll_ghost_candidates`:
|
||||
local ghosts, runtime = SS13.await(SS13.global_proc, "poll_ghost_candidates", "Would you like to be considered for something?")
|
||||
```
|
||||
|
||||
### SS13.wait(time, timer)
|
||||
## SS13.wait(time, timer)
|
||||
Waits for a number of **seconds** specified with the `time` argument. You can optionally specify a timer subsystem using the `timer` argument.
|
||||
|
||||
Internally, this function creates a timer that will resume the current task after `time` seconds, then yields the current task by calling `coroutine.yield` with no arguments and ignores the return values. If the task is prematurely resumed, the timer will be safely deleted.
|
||||
|
||||
### SS13.register_signal(datum, signal, func, make_easy_clear_function)
|
||||
## SS13.register_signal(datum, signal, func)
|
||||
Registers the Lua function `func` as a handler for `signal` on `datum`.
|
||||
|
||||
Like with signal handlers written in DM, Lua signal handlers should not sleep (either by calling `sleep` or `coroutine.yield`).
|
||||
|
||||
If `make_easy_clear_function` is truthy, a member function taking no arguments will be created in the `SS13` table to easily unregister the signal handler.
|
||||
|
||||
This function returns the `/datum/callback` created to call `func` from DM.
|
||||
This function returns whether the signal registration was successful.
|
||||
|
||||
The following example defines a function which will register a signal that makes `target` make a honking sound any time it moves:
|
||||
```lua
|
||||
function honk(target)
|
||||
SS13.register_signal(target, "movable_moved", function(source)
|
||||
dm.global_proc("playsound", target, "sound/items/bikehorn.ogg", 100, true)
|
||||
dm.global_procs.playsound(target, "sound/items/bikehorn.ogg", 100, true)
|
||||
end)
|
||||
end
|
||||
```
|
||||
|
||||
### SS13.unregister_signal(datum, signal, callback)
|
||||
Unregister a signal previously registered using `SS13.register_signal`. `callback` should be a `datum/callback` previously returned by `SS13.register_signal`. If `callback` is not specified, **ALL** signal handlers registered on `datum` for `signal` will be unregistered.
|
||||
NOTE: if `func` is an anonymous function declared inside the call to `SS13.register_signal`, it cannot be referenced in order to unregister that signal with `SS13.unregister_signal`
|
||||
|
||||
### SS13.set_timeout(time, func)
|
||||
## SS13.unregister_signal(datum, signal, func)
|
||||
Unregister a signal previously registered using `SS13.register_signal`. `func` must be a function for which a handler for the specified signal has already been registered. If `func` is `nil`, all handlers for that signal will be unregistered.
|
||||
|
||||
## SS13.set_timeout(time, func)
|
||||
Creates a timer which will execute `func` after `time` **seconds**. `func` should not expect to be passed any arguments, as it will not be passed any. Unlike `SS13.wait`, `SS13.set_timeout` does not yield or sleep the current task, making it suitable for use in signal handlers for `SS13.register_signal`
|
||||
|
||||
The following example will output a message to chat after 5 seconds:
|
||||
```lua
|
||||
SS13.set_timeout(5, function()
|
||||
dm.global_proc("to_chat", dm.world, "Hello World!")
|
||||
dm.global_procs.to_chat(dm.world, "Hello World!")
|
||||
end)
|
||||
```
|
||||
|
||||
### SS13.start_loop(time, amount, func)
|
||||
## SS13.start_loop(time, amount, func)
|
||||
Creates a timer which will execute `func` after `time` **seconds**. `func` should not expect to be passed any arguments, as it will not be passed any. Works exactly the same as `SS13.set_timeout` except it will loop the timer `amount` times. If `amount` is set to -1, it will loop indefinitely. Returns a number value, which represents the timer's id. Can be stopped with `SS13.end_loop`
|
||||
Returns a number, the timer id, which is needed to stop indefinite timers.
|
||||
The following example will output a message to chat every 5 seconds, repeating 10 times:
|
||||
```lua
|
||||
SS13.start_loop(5, 10, function()
|
||||
dm.global_proc("to_chat", dm.world, "Hello World!")
|
||||
dm.global_procs.to_chat(dm.world, "Hello World!")
|
||||
end)
|
||||
```
|
||||
The following example will output a message to chat every 5 seconds, until `SS13.end_loop(timerid)` is called:
|
||||
```lua
|
||||
local timerid = SS13.start_loop(5, -1, function()
|
||||
dm.global_proc("to_chat", dm.world, "Hello World!")
|
||||
dm.global_proc.to_chat(dm.world, "Hello World!")
|
||||
end)
|
||||
```
|
||||
|
||||
### SS13.end_loop(id)
|
||||
## SS13.end_loop(id)
|
||||
Prematurely ends a loop that hasn't ended yet, created with `SS13.start_loop`. Silently fails if there is no started loop with the specified id.
|
||||
The following example will output a message to chat every 5 seconds and delete it after it has repeated 20 times:
|
||||
```lua
|
||||
@@ -254,7 +322,7 @@ local repeated_amount = 0
|
||||
-- timerid won't be in the looping function's scope if declared before the function is declared.
|
||||
local timerid
|
||||
timerid = SS13.start_loop(5, -1, function()
|
||||
dm.global_proc("to_chat", dm.world, "Hello World!")
|
||||
dm.global_procs.to_chat(dm.world, "Hello World!")
|
||||
repeated_amount += 1
|
||||
if repeated_amount >= 20 then
|
||||
SS13.end_loop(timerid)
|
||||
@@ -262,35 +330,6 @@ timerid = SS13.start_loop(5, -1, function()
|
||||
end)
|
||||
```
|
||||
|
||||
### SS13.stop_all_loops()
|
||||
## SS13.stop_all_loops()
|
||||
Stops all current running loops that haven't ended yet.
|
||||
Useful in case you accidentally left a indefinite loop running without storing the id anywhere.
|
||||
|
||||
### SS13.stop_tracking(datum)
|
||||
Stops tracking a datum that was created via `SS13.new` so that it can be garbage collected and deleted without having to qdel. Should be used for things like callbacks and other such datums where the reference to the variable is no longer needed.
|
||||
|
||||
---
|
||||
|
||||
## Internal globals
|
||||
|
||||
Auxlua defines several registry values for each state. Note that there is no way to access registry values from lua code.
|
||||
|
||||
### sleep_flag
|
||||
|
||||
This flag is used to designate that a yielding task should be put in the sleep queue instead of the yield table. Once auxlua determines that a task should sleep, `sleep_flag` is cleared.
|
||||
|
||||
### sleep_queue
|
||||
|
||||
A sequence of threads, each corresponding to a task that has slept. When calling `/proc/__lua_awaken`, auxlua will dequeue the first thread from the sequence and resume it.
|
||||
|
||||
### yield_table
|
||||
|
||||
A table of threads, each corresponding to a coroutine that has yielded. When calling `/proc/__lua_resume`, auxlua will look for a thread at the index specified in the `index` argument, and resume it with the arguments specified in the `arguments` argument.
|
||||
|
||||
### task_info
|
||||
|
||||
A table of key-value-pairs, where the keys are threads, and the values are tables consisting of the following fields:
|
||||
|
||||
- name: A string containing the name of the task
|
||||
- status: A string, either "sleep" or "yield"
|
||||
- index: The task's index in `sleep_queue` or `yield_table`
|
||||
|
||||
@@ -1,239 +0,0 @@
|
||||
/datum
|
||||
var/__auxtools_weakref_id //used by auxtools for weak references
|
||||
|
||||
/**
|
||||
* Sets a global proc to call in place of just outright setting a datum's var to a given value
|
||||
*
|
||||
* The proc will be called with the arguments (datum/datum_to_modify, var_name, value)
|
||||
*
|
||||
* required wrapper text the name of the proc to use as the wrapper
|
||||
*/
|
||||
/proc/__lua_set_set_var_wrapper(wrapper)
|
||||
CRASH("auxlua not loaded")
|
||||
|
||||
/**
|
||||
* Sets a global proc to call in place of just outright calling a given proc on a datum
|
||||
*
|
||||
* The proc will be called with the arguments (datum/thing_to_call, proc_to_call, list/arguments)
|
||||
*
|
||||
* required wrapper text the name of the proc to use as the wrapper
|
||||
*/
|
||||
/proc/__lua_set_datum_proc_call_wrapper(wrapper)
|
||||
CRASH("auxlua not loaded")
|
||||
|
||||
/**
|
||||
* Sets a global proc to call in place of just outright calling a given global proc
|
||||
*
|
||||
* The proc will be called with the arguments (proc_to_call, list/arguments)
|
||||
*
|
||||
* required wrapper text the name of the proc to use as the wrapper
|
||||
*/
|
||||
/proc/__lua_set_global_proc_call_wrapper(wrapper)
|
||||
CRASH("auxlua not loaded")
|
||||
|
||||
/**
|
||||
* Sets a global proc as a wrapper for lua's print function
|
||||
*
|
||||
* The proc will be called with the arguments (state_id, list/arguments)
|
||||
*
|
||||
* required wrapper text the name of the proc to use as the wrapper
|
||||
*/
|
||||
/proc/__lua_set_print_wrapper(wrapper)
|
||||
CRASH("auxlua not loaded")
|
||||
|
||||
/**
|
||||
* Sets the maximum amount of time a lua chunk or function can execute without sleeping or yielding.
|
||||
* Chunks/functions that exceed this duration will produce an error.
|
||||
*
|
||||
* required limit number the execution limit, in milliseconds
|
||||
*/
|
||||
/proc/__lua_set_execution_limit(limit)
|
||||
CRASH("auxlua not loaded")
|
||||
|
||||
/**
|
||||
* Creates a new lua state.
|
||||
*
|
||||
* return text a pointer to the created state.
|
||||
*/
|
||||
/proc/__lua_new_state()
|
||||
CRASH("auxlua not loaded")
|
||||
|
||||
/**
|
||||
* Loads a chunk of lua source code and executes it
|
||||
*
|
||||
* required state text a pointer to the state
|
||||
* in which to execute the code
|
||||
* required script text the lua source code to execute
|
||||
* optional name text a name to give to the chunk
|
||||
*
|
||||
* return list|text a list of lua return information
|
||||
* or an error message if the state was corrupted
|
||||
*
|
||||
* Lua return information is formatted as followed:
|
||||
* - ["status"]: How the chunk or function stopped code execution
|
||||
* - "sleeping": The chunk or function called dm.sleep,
|
||||
* placing it in the sleep queue. Items in the sleep
|
||||
* queue can be resumed using /proc/__lua_awaken
|
||||
* - "yielded": The chunk or function called coroutine.yield,
|
||||
* placing it in the yield table. Items in the yield
|
||||
* table can can be resumed by passing their index
|
||||
* to /proc/__lua_resume
|
||||
* - "finished": The chunk or function finished
|
||||
* - "errored": The chunk or function produced an error
|
||||
* - "bad return": The chunk or function yielded or finished,
|
||||
* but its return value could not be converted to DM values
|
||||
* - ["param"]: Depends on status.
|
||||
* - "sleeping": null
|
||||
* - "yielded" or "finished": The return/yield value(s)
|
||||
* - "errored" or "bad return": The error message
|
||||
* - ["yield_index"]: The index in the yield table where the
|
||||
* chunk or function is located, for calls to __lua_resume
|
||||
* - ["name"]: The name of the chunk or function, for logging
|
||||
*/
|
||||
/proc/__lua_load(state, script, name)
|
||||
CRASH("auxlua not loaded")
|
||||
|
||||
/**
|
||||
* Calls a lua function
|
||||
*
|
||||
* required state text a pointer to the state
|
||||
* in which to call the function
|
||||
* required function text the name of the function to call
|
||||
* optional arguments list arguments to pass to the function
|
||||
*
|
||||
* return list|text a list of lua return information
|
||||
* or an error message if the state was corrupted
|
||||
*
|
||||
* Lua return information is formatted as followed:
|
||||
* - ["status"]: How the chunk or function stopped code execution
|
||||
* - "sleeping": The chunk or function called dm.sleep,
|
||||
* placing it in the sleep queue. Items in the sleep
|
||||
* queue can be resumed using /proc/__lua_awaken
|
||||
* - "yielded": The chunk or function called coroutine.yield,
|
||||
* placing it in the yield table. Items in the yield
|
||||
* table can can be resumed by passing their index
|
||||
* to /proc/__lua_resume
|
||||
* - "finished": The chunk or function finished
|
||||
* - "errored": The chunk or function produced an error
|
||||
* - "bad return": The chunk or function yielded or finished,
|
||||
* but its return value could not be converted to DM values
|
||||
* - ["param"]: Depends on status.
|
||||
* - "sleeping": null
|
||||
* - "yielded" or "finished": The return/yield value(s)
|
||||
* - "errored" or "bad return": The error message
|
||||
* - ["yield_index"]: The index in the yield table where the
|
||||
* chunk or function is located, for calls to __lua_resume
|
||||
* - ["name"]: The name of the chunk or function, for logging
|
||||
*/
|
||||
/proc/__lua_call(state, function, arguments)
|
||||
CRASH("auxlua not loaded")
|
||||
|
||||
/**
|
||||
* Dequeues the task at the front of the sleep queue and resumes it
|
||||
*
|
||||
* required state text a pointer to the state in which
|
||||
* to resume a task
|
||||
*
|
||||
* return list|text|null a list of lua return information,
|
||||
* an error message if the state is corrupted,
|
||||
* or null if the sleep queue is empty
|
||||
*
|
||||
* Lua return information is formatted as followed:
|
||||
* - ["status"]: How the chunk or function stopped code execution
|
||||
* - "sleeping": The chunk or function called dm.sleep,
|
||||
* placing it in the sleep queue. Items in the sleep
|
||||
* queue can be resumed using /proc/__lua_awaken
|
||||
* - "yielded": The chunk or function called coroutine.yield,
|
||||
* placing it in the yield table. Items in the yield
|
||||
* table can can be resumed by passing their index
|
||||
* to /proc/__lua_resume
|
||||
* - "finished": The chunk or function finished
|
||||
* - "errored": The chunk or function produced an error
|
||||
* - "bad return": The chunk or function yielded or finished,
|
||||
* but its return value could not be converted to DM values
|
||||
* - ["param"]: Depends on status.
|
||||
* - "sleeping": null
|
||||
* - "yielded" or "finished": The return/yield value(s)
|
||||
* - "errored" or "bad return": The error message
|
||||
* - ["yield_index"]: The index in the yield table where the
|
||||
* chunk or function is located, for calls to __lua_resume
|
||||
* - ["name"]: The name of the chunk or function, for logging
|
||||
*/
|
||||
/proc/__lua_awaken(state)
|
||||
CRASH("auxlua not loaded")
|
||||
|
||||
/**
|
||||
* Removes the task at the specified index from the yield table
|
||||
* and resumes it
|
||||
*
|
||||
* required state text a pointer to the state in which to
|
||||
* resume a task
|
||||
* required index number the index in the yield table of the
|
||||
* task to resume
|
||||
* optional arguments list the arguments to resume the task with
|
||||
*
|
||||
* return list|text|null a list of lua return information,
|
||||
* an error message if the state is corrupted,
|
||||
* or null if there is no task at the specified index
|
||||
*
|
||||
* Lua return information is formatted as followed:
|
||||
* - ["status"]: How the chunk or function stopped code execution
|
||||
* - "sleeping": The chunk or function called dm.sleep,
|
||||
* placing it in the sleep queue. Items in the sleep
|
||||
* queue can be resumed using /proc/__lua_awaken
|
||||
* - "yielded": The chunk or function called coroutine.yield,
|
||||
* placing it in the yield table. Items in the yield
|
||||
* table can can be resumed by passing their index
|
||||
* to /proc/__lua_resume
|
||||
* - "finished": The chunk or function finished
|
||||
* - "errored": The chunk or function produced an error
|
||||
* - "bad return": The chunk or function yielded or finished,
|
||||
* but its return value could not be converted to DM values
|
||||
* - ["param"]: Depends on status.
|
||||
* - "sleeping": null
|
||||
* - "yielded" or "finished": The return/yield value(s)
|
||||
* - "errored" or "bad return": The error message
|
||||
* - ["yield_index"]: The index in the yield table where the
|
||||
* chunk or function is located, for calls to __lua_resume
|
||||
* - ["name"]: The name of the chunk or function, for logging
|
||||
*/
|
||||
/proc/__lua_resume(state, index, arguments)
|
||||
CRASH("auxlua not loaded")
|
||||
|
||||
/**
|
||||
* Get the variables within a state's environment.
|
||||
* Values not convertible to DM values are substituted
|
||||
* for their types as text
|
||||
*
|
||||
* required state text a pointer to the state
|
||||
* to get the variables from
|
||||
*
|
||||
* return list the variables of the state's environment
|
||||
*/
|
||||
/proc/__lua_get_globals(state)
|
||||
CRASH("auxlua not loaded")
|
||||
|
||||
/**
|
||||
* Get a list of all tasks currently in progress within a state
|
||||
*
|
||||
* required state text a pointer to the state
|
||||
* to get the tasks from
|
||||
*
|
||||
* return list a list of the state's tasks, formatted as follows:
|
||||
* - name: The name of the task
|
||||
* - status: Whether the task is sleeping or yielding
|
||||
* - index: The index of the task in the sleep queue
|
||||
* or yield table, whichever is applicable
|
||||
*/
|
||||
/proc/__lua_get_tasks(state)
|
||||
CRASH("auxlua not loaded")
|
||||
|
||||
/**
|
||||
* Kills a task in progress
|
||||
*
|
||||
* required state text a pointer to the state
|
||||
* in which to kill a task
|
||||
* required info list the task info
|
||||
*/
|
||||
/proc/__lua_kill_task(state, info)
|
||||
CRASH("auxlua not loaded")
|
||||
@@ -1,3 +1,12 @@
|
||||
/proc/wrap_lua_get_var(datum/thing, var_name)
|
||||
SHOULD_NOT_SLEEP(TRUE)
|
||||
if(thing == world)
|
||||
return world.vars[var_name]
|
||||
if(ref(thing) == "\[0xe000001\]") //This weird fucking thing is like global.vars, but it's not a list and vars is not a valid index for it and I really don't fucking know.
|
||||
return global.vars[var_name]
|
||||
if(thing.can_vv_get(var_name))
|
||||
return thing.vars[var_name]
|
||||
|
||||
/proc/wrap_lua_set_var(datum/thing_to_set, var_name, value)
|
||||
SHOULD_NOT_SLEEP(TRUE)
|
||||
thing_to_set.vv_edit_var(var_name, value)
|
||||
@@ -11,8 +20,6 @@
|
||||
ret = WrapAdminProcCall(thing_to_call, proc_name, arguments)
|
||||
else
|
||||
ret = HandleUserlessProcCall("lua", thing_to_call, proc_name, arguments)
|
||||
if(isdatum(ret))
|
||||
SSlua.gc_guard += ret
|
||||
return ret
|
||||
|
||||
/proc/wrap_lua_global_proc_call(proc_name, list/arguments)
|
||||
@@ -24,8 +31,6 @@
|
||||
ret = WrapAdminProcCall(GLOBAL_PROC, proc_name, arguments)
|
||||
else
|
||||
ret = HandleUserlessProcCall("lua", GLOBAL_PROC, proc_name, arguments)
|
||||
if(isdatum(ret))
|
||||
SSlua.gc_guard += ret
|
||||
return ret
|
||||
|
||||
/proc/wrap_lua_print(state_id, list/arguments)
|
||||
@@ -38,6 +43,6 @@
|
||||
if(!target_state)
|
||||
return
|
||||
var/print_message = jointext(arguments, "\t")
|
||||
var/result = list("status" = "print", "param" = print_message)
|
||||
var/result = list("status" = "print", "message" = print_message)
|
||||
INVOKE_ASYNC(target_state, TYPE_PROC_REF(/datum/lua_state, log_result), result, TRUE)
|
||||
log_lua("[target_state]: [print_message]")
|
||||
|
||||
@@ -3,27 +3,27 @@
|
||||
#define PROMISE_REJECTED 2
|
||||
|
||||
/**
|
||||
* Auxtools hooks act as "set waitfor = 0" procs. This means that whenever
|
||||
* a proc directly called from auxtools sleeps, the hook returns with whatever
|
||||
* Byondapi hooks act as "set waitfor = 0" procs. This means that whenever
|
||||
* a proc directly called from an external library sleeps, the hook returns with whatever
|
||||
* the called proc had as its return value at the moment it slept. This may not
|
||||
* be desired behavior, so this datum exists to wrap these procs.
|
||||
*
|
||||
* Some procs that don't sleep could take longer than the execution limit would
|
||||
* allow for. We can wrap these in a promise as well.
|
||||
*/
|
||||
/datum/auxtools_promise
|
||||
/datum/promise
|
||||
var/datum/callback/callback
|
||||
var/return_value
|
||||
var/runtime_message
|
||||
var/status = PROMISE_PENDING
|
||||
|
||||
/datum/auxtools_promise/New(...)
|
||||
/datum/promise/New(...)
|
||||
if(!usr)
|
||||
usr = GLOB.lua_usr
|
||||
callback = CALLBACK(arglist(args))
|
||||
perform()
|
||||
INVOKE_ASYNC(src, PROC_REF(perform))
|
||||
|
||||
/datum/auxtools_promise/proc/perform()
|
||||
set waitfor = 0
|
||||
sleep() //In case we have to call a super-expensive non-sleeping proc (like getFlatIcon)
|
||||
/datum/promise/proc/perform()
|
||||
try
|
||||
return_value = callback.Invoke()
|
||||
status = PROMISE_RESOLVED
|
||||
|
||||
@@ -16,6 +16,12 @@
|
||||
/// If set, we will force the editor to look at this chunk
|
||||
var/force_view_chunk
|
||||
|
||||
/// If set, we will force the script input to be this
|
||||
var/force_input
|
||||
|
||||
/// If set, the latest code execution performed from the editor raised an error, and this is the message from that error
|
||||
var/last_error
|
||||
|
||||
/datum/lua_editor/New(state, _quick_log_index)
|
||||
. = ..()
|
||||
if(state)
|
||||
@@ -37,37 +43,51 @@
|
||||
/datum/lua_editor/ui_state(mob/user)
|
||||
return GLOB.debug_state
|
||||
|
||||
/datum/lua_editor/ui_static_data(mob/user)
|
||||
var/list/data = list()
|
||||
data["documentation"] = file2text('code/modules/admin/verbs/lua/README.md')
|
||||
data["auxtools_enabled"] = CONFIG_GET(flag/auxtools_enabled)
|
||||
data["ss_lua_init"] = SSlua.initialized
|
||||
return data
|
||||
|
||||
/datum/lua_editor/ui_data(mob/user)
|
||||
var/list/data = list()
|
||||
if(!CONFIG_GET(flag/auxtools_enabled) || !SSlua.initialized)
|
||||
data["ss_lua_init"] = SSlua.initialized
|
||||
if(!SSlua.initialized)
|
||||
return data
|
||||
|
||||
data["noStateYet"] = !current_state
|
||||
data["showGlobalTable"] = show_global_table
|
||||
if(current_state)
|
||||
if(current_state.log)
|
||||
data["stateLog"] = kvpify_list(refify_list(current_state.log.Copy((page*50)+1, min((page+1)*50+1, current_state.log.len+1))))
|
||||
var/list/logs = current_state.log.Copy((page*50)+1, min((page+1)*50+1, current_state.log.len+1))
|
||||
for(var/i in 1 to logs.len)
|
||||
var/list/log = logs[i]
|
||||
log = log.Copy()
|
||||
if(log["return_values"])
|
||||
log["return_values"] = kvpify_list(prepare_lua_editor_list(deep_copy_without_cycles(log["return_values"])))
|
||||
logs[i] = log
|
||||
data["stateLog"] = logs
|
||||
data["page"] = page
|
||||
data["pageCount"] = CEILING(current_state.log.len/50, 1)
|
||||
data["tasks"] = current_state.get_tasks()
|
||||
if(show_global_table)
|
||||
current_state.get_globals()
|
||||
data["globals"] = kvpify_list(refify_list(current_state.globals))
|
||||
data["states"] = SSlua.states
|
||||
data["callArguments"] = kvpify_list(refify_list(arguments))
|
||||
var/list/values = current_state.globals["values"]
|
||||
values = deep_copy_without_cycles(values)
|
||||
values = prepare_lua_editor_list(values)
|
||||
values = kvpify_list(values)
|
||||
var/list/variants = current_state.globals["variants"]
|
||||
data["globals"] = list("values" = values, "variants" = variants)
|
||||
if(last_error)
|
||||
data["lastError"] = last_error
|
||||
last_error = null
|
||||
data["states"] = list()
|
||||
for(var/datum/lua_state/state as anything in SSlua.states)
|
||||
data["states"] += state.display_name
|
||||
data["callArguments"] = kvpify_list(prepare_lua_editor_list(deep_copy_without_cycles(arguments)))
|
||||
if(force_modal)
|
||||
data["forceModal"] = force_modal
|
||||
force_modal = null
|
||||
if(force_view_chunk)
|
||||
data["forceViewChunk"] = force_view_chunk
|
||||
force_view_chunk = null
|
||||
if(force_input)
|
||||
data["force_input"] = force_input
|
||||
force_input = null
|
||||
return data
|
||||
|
||||
/datum/lua_editor/proc/traverse_list(list/path, list/root, traversal_depth_offset = 0)
|
||||
@@ -99,6 +119,15 @@
|
||||
else
|
||||
return root
|
||||
|
||||
/datum/lua_editor/proc/run_code(code)
|
||||
var/ckey = usr.ckey
|
||||
current_state.ckey_last_runner = ckey
|
||||
var/result = current_state.load_script(code)
|
||||
var/index_with_result = current_state.log_result(result)
|
||||
if(result["status"] == "error")
|
||||
last_error = result["message"]
|
||||
message_admins("[key_name(usr)] executed [length(code)] bytes of lua code. [ADMIN_LUAVIEW_CHUNK(current_state, index_with_result)]")
|
||||
|
||||
/datum/lua_editor/ui_act(action, list/params)
|
||||
. = ..()
|
||||
if(.)
|
||||
@@ -116,6 +145,8 @@
|
||||
if(!length(state_name))
|
||||
return TRUE
|
||||
var/datum/lua_state/new_state = new(state_name)
|
||||
if(QDELETED(new_state))
|
||||
return
|
||||
SSlua.states += new_state
|
||||
LAZYREMOVEASSOC(SSlua.editors, text_ref(current_state), src)
|
||||
current_state = new_state
|
||||
@@ -130,11 +161,14 @@
|
||||
page = 0
|
||||
return TRUE
|
||||
if("runCode")
|
||||
var/code = params["code"]
|
||||
current_state.ckey_last_runner = usr.ckey
|
||||
var/result = current_state.load_script(code)
|
||||
var/index_with_result = current_state.log_result(result)
|
||||
message_admins("[key_name(usr)] executed [length(code)] bytes of lua code. [ADMIN_LUAVIEW_CHUNK(current_state, index_with_result)]")
|
||||
run_code(params["code"])
|
||||
return TRUE
|
||||
if("runFile")
|
||||
var/code_file = input(usr, "Select a script to run.", "Lua") as file|null
|
||||
if(!code_file)
|
||||
return TRUE
|
||||
var/code = file2text(code_file)
|
||||
run_code(code)
|
||||
return TRUE
|
||||
if("moveArgUp")
|
||||
var/list/path = params["path"]
|
||||
@@ -168,27 +202,31 @@
|
||||
return TRUE
|
||||
if("callFunction")
|
||||
var/list/recursive_indices = params["indices"]
|
||||
var/list/current_list = kvpify_list(current_state.globals)
|
||||
var/list/current_list = kvpify_list(current_state.globals["values"])
|
||||
var/list/current_variants = current_state.globals["variants"]
|
||||
var/function = list()
|
||||
while(LAZYLEN(recursive_indices))
|
||||
var/index = popleft(recursive_indices)
|
||||
var/list/element = current_list[index]
|
||||
var/key = element["key"]
|
||||
var/value = element["value"]
|
||||
if(!(istext(key) || isnum(key)))
|
||||
to_chat(usr, span_warning("invalid key \[[key]] for function call (expected text or num)"))
|
||||
var/list/variant_pair = current_variants[index]
|
||||
var/key_variant = variant_pair["key"]
|
||||
if(key_variant == "function" || key_variant == "thread" || key_variant == "userdata" || key_variant == "error_as_value")
|
||||
to_chat(usr, span_warning("invalid table key \[[key]] for function call (expected text, num, path, list, or ref, got [key_variant])"))
|
||||
return
|
||||
function += key
|
||||
if(islist(value))
|
||||
current_list = value
|
||||
current_variants = variant_pair["value"]
|
||||
else
|
||||
var/regex/function_regex = regex("^function: 0x\[0-9a-fA-F]+$")
|
||||
if(function_regex.Find(value))
|
||||
break
|
||||
to_chat(usr, span_warning("invalid path element \[[value]] for function call (expected list or text matching [function_regex])"))
|
||||
return
|
||||
if(variant_pair["value"] != "function")
|
||||
to_chat(usr, span_warning("invalid value \[[value]] for function call (expected list or function)"))
|
||||
return
|
||||
var/result = current_state.call_function(arglist(list(function) + arguments))
|
||||
current_state.log_result(result)
|
||||
if(result["status"] == "error")
|
||||
last_error = result["message"]
|
||||
arguments.Cut()
|
||||
return TRUE
|
||||
if("resumeTask")
|
||||
@@ -197,20 +235,21 @@
|
||||
arguments.Cut()
|
||||
return TRUE
|
||||
if("killTask")
|
||||
var/task_info = params["info"]
|
||||
SSlua.kill_task(current_state, task_info)
|
||||
var/is_sleep = params["is_sleep"]
|
||||
var/index = params["index"]
|
||||
SSlua.kill_task(current_state, is_sleep, index)
|
||||
return TRUE
|
||||
if("vvReturnValue")
|
||||
var/log_entry_index = params["entryIndex"]
|
||||
var/list/log_entry = current_state.log[log_entry_index]
|
||||
var/thing_to_debug = traverse_list(params["tableIndices"], log_entry["param"])
|
||||
var/thing_to_debug = traverse_list(params["indices"], log_entry["return_values"])
|
||||
if(isweakref(thing_to_debug))
|
||||
var/datum/weakref/ref = thing_to_debug
|
||||
thing_to_debug = ref.resolve()
|
||||
INVOKE_ASYNC(usr.client, TYPE_PROC_REF(/client, debug_variables), thing_to_debug)
|
||||
return FALSE
|
||||
if("vvGlobal")
|
||||
var/thing_to_debug = traverse_list(params["indices"], current_state.globals)
|
||||
var/thing_to_debug = traverse_list(params["indices"], current_state.globals["values"])
|
||||
if(isweakref(thing_to_debug))
|
||||
var/datum/weakref/ref = thing_to_debug
|
||||
thing_to_debug = ref.resolve()
|
||||
@@ -228,6 +267,9 @@
|
||||
if("previousPage")
|
||||
page = max(page-1, 0)
|
||||
return TRUE
|
||||
if("nukeLog")
|
||||
current_state.log.Cut()
|
||||
return TRUE
|
||||
|
||||
/datum/lua_editor/ui_close(mob/user)
|
||||
. = ..()
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
#define MAX_LOG_REPEAT_LOOKBACK 5
|
||||
|
||||
GLOBAL_VAR_INIT(IsLuaCall, FALSE)
|
||||
GLOBAL_PROTECT(IsLuaCall)
|
||||
|
||||
GLOBAL_DATUM(lua_usr, /mob)
|
||||
GLOBAL_PROTECT(lua_usr)
|
||||
|
||||
/datum/lua_state
|
||||
var/name
|
||||
GLOBAL_LIST_EMPTY_TYPED(lua_state_stack, /datum/weakref)
|
||||
GLOBAL_PROTECT(lua_state_stack)
|
||||
|
||||
/// The internal ID of the lua state stored in auxlua's global map
|
||||
/datum/lua_state
|
||||
var/display_name
|
||||
|
||||
/// The internal ID of the lua state stored in dreamluau's state list
|
||||
var/internal_id
|
||||
|
||||
/// A log of every return, yield, and error for each chunk execution and function call
|
||||
@@ -18,9 +18,6 @@ GLOBAL_PROTECT(lua_usr)
|
||||
/// A list of all the variables in the state's environment
|
||||
var/list/globals = list()
|
||||
|
||||
/// A list in which to store datums and lists instantiated in lua, ensuring that they don't get garbage collected
|
||||
var/list/references = list()
|
||||
|
||||
/// Ckey of the last user who ran a script on this lua state.
|
||||
var/ckey_last_runner = ""
|
||||
|
||||
@@ -39,55 +36,65 @@ GLOBAL_PROTECT(lua_usr)
|
||||
if(SSlua.initialized != TRUE)
|
||||
qdel(src)
|
||||
return
|
||||
name = _name
|
||||
internal_id = __lua_new_state()
|
||||
display_name = _name
|
||||
internal_id = DREAMLUAU_NEW_STATE()
|
||||
if(!isnum(internal_id))
|
||||
stack_trace(internal_id)
|
||||
qdel(src)
|
||||
|
||||
/datum/lua_state/proc/check_if_slept(result)
|
||||
if(result["status"] == "sleeping")
|
||||
if(result["status"] == "sleep")
|
||||
SSlua.sleeps += src
|
||||
|
||||
/datum/lua_state/proc/log_result(result, verbose = TRUE)
|
||||
if(!islist(result))
|
||||
return
|
||||
if(!verbose && result["status"] != "errored" && result["status"] != "bad return" \
|
||||
&& !(result["name"] == "input" && (result["status"] == "finished" || length(result["param"]))))
|
||||
var/status = result["status"]
|
||||
if(!verbose && status != "error" && status != "panic" && status != "runtime" && !(result["name"] == "input" && (status == "finished" || length(result["return_values"]))))
|
||||
return
|
||||
var/append_to_log = TRUE
|
||||
var/index_of_log
|
||||
if(log.len)
|
||||
for(var/index in log.len to max(log.len - MAX_LOG_REPEAT_LOOKBACK, 1) step -1)
|
||||
var/list/entry = log[index]
|
||||
if(entry["status"] == result["status"] \
|
||||
&& entry["chunk"] == result["chunk"] \
|
||||
&& entry["name"] == result["name"] \
|
||||
&& ((entry["param"] == result["param"]) || deep_compare_list(entry["param"], result["param"])))
|
||||
if(!entry["repeats"])
|
||||
entry["repeats"] = 0
|
||||
index_of_log = index
|
||||
entry["repeats"]++
|
||||
append_to_log = FALSE
|
||||
break
|
||||
if(!compare_lua_logs(entry, result))
|
||||
continue
|
||||
if(!entry["repeats"])
|
||||
entry["repeats"] = 0
|
||||
index_of_log = index
|
||||
entry["repeats"]++
|
||||
append_to_log = FALSE
|
||||
break
|
||||
if(append_to_log)
|
||||
if(islist(result["param"]))
|
||||
result["param"] = weakrefify_list(encode_text_and_nulls(result["param"]))
|
||||
if(islist(result["return_values"]))
|
||||
add_lua_return_value_variants(result["return_values"], result["variants"])
|
||||
result["return_values"] = weakrefify_list(result["return_values"])
|
||||
log += list(result)
|
||||
index_of_log = log.len
|
||||
INVOKE_ASYNC(src, TYPE_PROC_REF(/datum/lua_state, update_editors))
|
||||
return index_of_log
|
||||
|
||||
/datum/lua_state/proc/parse_error(message, name)
|
||||
if(copytext(message, 1, 7) == "PANIC:")
|
||||
return list("status" = "panic", "message" = copytext(message, 7), "name" = name)
|
||||
else
|
||||
return list("status" = "error", "message" = message, "name" = name)
|
||||
|
||||
/datum/lua_state/proc/load_script(script)
|
||||
GLOB.IsLuaCall = TRUE
|
||||
var/tmp_usr = GLOB.lua_usr
|
||||
GLOB.lua_usr = usr
|
||||
var/result = __lua_load(internal_id, script)
|
||||
GLOB.IsLuaCall = FALSE
|
||||
DREAMLUAU_SET_USR
|
||||
GLOB.lua_state_stack += WEAKREF(src)
|
||||
var/result = DREAMLUAU_LOAD(internal_id, script, "input")
|
||||
SSlua.needs_gc_cycle |= src
|
||||
pop(GLOB.lua_state_stack)
|
||||
GLOB.lua_usr = tmp_usr
|
||||
|
||||
// Internal errors unrelated to the code being executed are returned as text rather than lists
|
||||
if(isnull(result))
|
||||
result = list("status" = "errored", "param" = "__lua_load returned null (it may have runtimed - check the runtime logs)", "name" = "input")
|
||||
result = list("status" = "error", "message" = "load returned null (it may have runtimed - check the runtime logs)", "name" = "input")
|
||||
if(istext(result))
|
||||
result = list("status" = "errored", "param" = result, "name" = "input")
|
||||
result = parse_error(result, "input")
|
||||
result["chunk"] = script
|
||||
check_if_slept(result)
|
||||
|
||||
@@ -109,67 +116,106 @@ GLOBAL_PROTECT(lua_usr)
|
||||
if(islist(function))
|
||||
var/list/new_function_path = list()
|
||||
for(var/path_element in function)
|
||||
new_function_path += path_element
|
||||
if(isweakref(path_element))
|
||||
var/datum/weakref/weak_ref = path_element
|
||||
var/resolved = weak_ref.hard_resolve()
|
||||
if(!resolved)
|
||||
return list("status" = "error", "message" = "Weakref in function path ([weak_ref] [text_ref(weak_ref)]) resolved to null.", "name" = jointext(function, "."))
|
||||
new_function_path += resolved
|
||||
else
|
||||
new_function_path += path_element
|
||||
function = new_function_path
|
||||
else
|
||||
function = list(function)
|
||||
|
||||
var/tmp_usr = GLOB.lua_usr
|
||||
GLOB.lua_usr = usr
|
||||
GLOB.IsLuaCall = TRUE
|
||||
var/result = __lua_call(internal_id, function, call_args)
|
||||
GLOB.IsLuaCall = FALSE
|
||||
DREAMLUAU_SET_USR
|
||||
GLOB.lua_state_stack += WEAKREF(src)
|
||||
var/result = DREAMLUAU_CALL_FUNCTION(internal_id, function, call_args)
|
||||
SSlua.needs_gc_cycle |= src
|
||||
pop(GLOB.lua_state_stack)
|
||||
GLOB.lua_usr = tmp_usr
|
||||
|
||||
if(isnull(result))
|
||||
result = list("status" = "errored", "param" = "__lua_call returned null (it may have runtimed - check the runtime logs)", "name" = islist(function) ? jointext(function, ".") : function)
|
||||
result = list("status" = "error", "message" = "call_function returned null (it may have runtimed - check the runtime logs)", "name" = jointext(function, "."))
|
||||
if(istext(result))
|
||||
result = list("status" = "errored", "param" = result, "name" = islist(function) ? jointext(function, ".") : function)
|
||||
result = parse_error(result, jointext(function, "."))
|
||||
check_if_slept(result)
|
||||
return result
|
||||
|
||||
/datum/lua_state/proc/call_function_return_first(function, ...)
|
||||
SHOULD_NOT_SLEEP(TRUE) // This function is meant to be used for signal handlers.
|
||||
var/list/result = call_function(arglist(args))
|
||||
log_result(result, verbose = FALSE)
|
||||
INVOKE_ASYNC(src, PROC_REF(log_result), deep_copy_list(result), /*verbose = */FALSE)
|
||||
if(length(result))
|
||||
if(islist(result["param"]) && length(result["param"]))
|
||||
return result["param"][1]
|
||||
if(islist(result["return_values"]) && length(result["return_values"]))
|
||||
var/return_value = result["return_values"][1]
|
||||
var/variant = (islist(result["variants"]) && length(result["variants"])) && result["variants"][1]
|
||||
if(islist(return_value) && islist(variant))
|
||||
remove_non_dm_variants(return_value, variant)
|
||||
return return_value
|
||||
|
||||
/datum/lua_state/proc/awaken()
|
||||
GLOB.IsLuaCall = TRUE
|
||||
var/result = __lua_awaken(internal_id)
|
||||
GLOB.IsLuaCall = FALSE
|
||||
DREAMLUAU_SET_USR
|
||||
GLOB.lua_state_stack += WEAKREF(src)
|
||||
var/result = DREAMLUAU_AWAKEN(internal_id)
|
||||
SSlua.needs_gc_cycle |= src
|
||||
pop(GLOB.lua_state_stack)
|
||||
|
||||
if(isnull(result))
|
||||
result = list("status" = "errored", "param" = "__lua_awaken returned null (it may have runtimed - check the runtime logs)", "name" = "An attempted awaken")
|
||||
result = list("status" = "error", "message" = "awaken returned null (it may have runtimed - check the runtime logs)", "name" = "An attempted awaken")
|
||||
if(istext(result))
|
||||
result = list("status" = "errored", "param" = result, "name" = "An attempted awaken")
|
||||
result = parse_error(result, "An attempted awaken")
|
||||
check_if_slept(result)
|
||||
return result
|
||||
|
||||
/// Prefer calling SSlua.queue_resume over directly calling this
|
||||
/datum/lua_state/proc/resume(index, ...)
|
||||
var/call_args = length(args) > 1 ? args.Copy(2) : list()
|
||||
var/msg = "[key_name(usr)] resumed a lua coroutine with arguments: [english_list(call_args)]"
|
||||
log_lua(msg)
|
||||
|
||||
GLOB.IsLuaCall = TRUE
|
||||
var/result = __lua_resume(internal_id, index, call_args)
|
||||
GLOB.IsLuaCall = FALSE
|
||||
DREAMLUAU_SET_USR
|
||||
GLOB.lua_state_stack += WEAKREF(src)
|
||||
var/result = DREAMLUAU_RESUME(internal_id, index, call_args)
|
||||
SSlua.needs_gc_cycle |= src
|
||||
pop(GLOB.lua_state_stack)
|
||||
|
||||
if(isnull(result))
|
||||
result = list("status" = "errored", "param" = "__lua_resume returned null (it may have runtimed - check the runtime logs)", "name" = "An attempted resume")
|
||||
result = list("status" = "error", "param" = "resume returned null (it may have runtimed - check the runtime logs)", "name" = "An attempted resume")
|
||||
if(istext(result))
|
||||
result = list("status" = "errored", "param" = result, "name" = "An attempted resume")
|
||||
result = parse_error(result, "An attempted resumt")
|
||||
check_if_slept(result)
|
||||
return result
|
||||
|
||||
/datum/lua_state/proc/get_globals()
|
||||
globals = weakrefify_list(encode_text_and_nulls(__lua_get_globals(internal_id)))
|
||||
var/result = DREAMLUAU_GET_GLOBALS(internal_id)
|
||||
if(isnull(result))
|
||||
CRASH("get_globals returned null")
|
||||
if(istext(result))
|
||||
CRASH(result)
|
||||
var/list/new_globals = result
|
||||
var/list/values = new_globals["values"]
|
||||
var/list/variants = new_globals["variants"]
|
||||
add_lua_editor_variants(values, variants)
|
||||
globals = list("values" = weakrefify_list(values), "variants" = variants)
|
||||
|
||||
/datum/lua_state/proc/get_tasks()
|
||||
return __lua_get_tasks(internal_id)
|
||||
var/result = DREAMLUAU_LIST_THREADS(internal_id)
|
||||
if(isnull(result))
|
||||
CRASH("list_threads returned null")
|
||||
if(istext(result))
|
||||
CRASH(result)
|
||||
return result
|
||||
|
||||
/datum/lua_state/proc/kill_task(task_info)
|
||||
__lua_kill_task(internal_id, task_info)
|
||||
/datum/lua_state/proc/kill_task(is_sleep, index)
|
||||
var/result = is_sleep ? DREAMLUAU_KILL_SLEEPING_THREAD(internal_id, index) : DREAMLUAU_KILL_YIELDED_THREAD(internal_id, index)
|
||||
SSlua.needs_gc_cycle |= src
|
||||
return result
|
||||
|
||||
/datum/lua_state/proc/collect_garbage()
|
||||
var/result = DREAMLUAU_COLLECT_GARBAGE(internal_id)
|
||||
if(!isnull(result))
|
||||
CRASH(result)
|
||||
|
||||
/datum/lua_state/proc/update_editors()
|
||||
var/list/editor_list = LAZYACCESS(SSlua.editors, text_ref(src))
|
||||
@@ -177,18 +223,4 @@ GLOBAL_PROTECT(lua_usr)
|
||||
for(var/datum/lua_editor/editor as anything in editor_list)
|
||||
SStgui.update_uis(editor)
|
||||
|
||||
/// Called by lua scripts when they add an atom to var/list/references so that it gets cleared up on delete.
|
||||
/datum/lua_state/proc/clear_on_delete(datum/to_clear)
|
||||
RegisterSignal(to_clear, COMSIG_QDELETING, PROC_REF(on_delete))
|
||||
|
||||
/// Called by lua scripts when an atom they've added should soft delete and this state should stop tracking it.
|
||||
/// Needs to unregister all signals.
|
||||
/datum/lua_state/proc/let_soft_delete(datum/to_clear)
|
||||
UnregisterSignal(to_clear, COMSIG_QDELETING, PROC_REF(on_delete))
|
||||
references -= to_clear
|
||||
|
||||
/datum/lua_state/proc/on_delete(datum/to_clear)
|
||||
SIGNAL_HANDLER
|
||||
references -= to_clear
|
||||
|
||||
#undef MAX_LOG_REPEAT_LOOKBACK
|
||||
|
||||
Reference in New Issue
Block a user