83 lines
2.2 KiB
GDScript3
83 lines
2.2 KiB
GDScript3
|
|
class_name ExprBase
|
||
|
|
extends RefCounted
|
||
|
|
## The base instance Godot's Expression calls helper functions on, for Expr:
|
||
|
|
## dice, dm(), if(), has(), count(), toward(), indirect @[…] names, and step
|
||
|
|
## names beside scale values (_lit).
|
||
|
|
|
||
|
|
var ctx: RollContext = null
|
||
|
|
var error: String = ""
|
||
|
|
## The expression's variables, in input order: [kind ("@" or ""), name].
|
||
|
|
var var_names: Array = []
|
||
|
|
|
||
|
|
|
||
|
|
func _d(n: int, sides: int) -> int:
|
||
|
|
if ctx != null and ctx.faces != null:
|
||
|
|
var total := 0
|
||
|
|
for k in n:
|
||
|
|
var f := ctx.rng.randi_range(1, sides)
|
||
|
|
(ctx.faces as Array).append(f)
|
||
|
|
total += f
|
||
|
|
return total
|
||
|
|
return Expr.roll_dice(n, sides, ctx.rng if ctx != null else null)
|
||
|
|
|
||
|
|
|
||
|
|
func dm(x: Variant) -> int:
|
||
|
|
return Expr.dm(x)
|
||
|
|
|
||
|
|
|
||
|
|
func _if(cond: Variant, then_value: Variant, else_value: Variant) -> Variant:
|
||
|
|
return then_value if Expr.truthy(cond) else else_value
|
||
|
|
|
||
|
|
|
||
|
|
func has(list: Variant, item: Variant) -> bool:
|
||
|
|
return Expr.has_item(list, item)
|
||
|
|
|
||
|
|
|
||
|
|
## One step from `a` toward `b` (scale positions or plain numbers).
|
||
|
|
func toward(a: Variant, b: Variant) -> int:
|
||
|
|
return Scales.toward(a, b)
|
||
|
|
|
||
|
|
|
||
|
|
## A text literal beside variable `slot`: when that variable is a scale and
|
||
|
|
## the text is one of its steps, the step's number; otherwise the text.
|
||
|
|
func _lit(slot: int, text: String) -> Variant:
|
||
|
|
if ctx == null or slot < 0 or slot >= var_names.size():
|
||
|
|
return text
|
||
|
|
var pair: Array = var_names[slot]
|
||
|
|
if pair[0] != "@":
|
||
|
|
return text
|
||
|
|
var steps := ctx.scale_steps(str(pair[1]))
|
||
|
|
if steps.is_empty():
|
||
|
|
return text
|
||
|
|
var k := Scales.position_of(steps, text)
|
||
|
|
return k if k > 0 else text
|
||
|
|
|
||
|
|
|
||
|
|
func _iv(name: Variant) -> Variant:
|
||
|
|
return _indirect(name, 0)
|
||
|
|
|
||
|
|
|
||
|
|
func _ivt(name: Variant) -> Variant:
|
||
|
|
return _indirect(name, "")
|
||
|
|
|
||
|
|
|
||
|
|
func _indirect(name: Variant, unset: Variant) -> Variant:
|
||
|
|
var r := Expr.indirect_name(name)
|
||
|
|
if r["error"] != "":
|
||
|
|
if error == "":
|
||
|
|
error = r["error"]
|
||
|
|
return unset
|
||
|
|
if ctx == null:
|
||
|
|
return unset
|
||
|
|
var v: Variant = ctx.get_value("@" + str(r["name"]))
|
||
|
|
var steps := ctx.scale_steps(str(r["name"]))
|
||
|
|
if not steps.is_empty():
|
||
|
|
return Scales.position_of(steps, v) if v != null else 0
|
||
|
|
return unset if v == null else Expr.to_value(v)
|
||
|
|
|
||
|
|
|
||
|
|
func count(prefix: Variant) -> int:
|
||
|
|
if ctx == null:
|
||
|
|
return 0
|
||
|
|
return ctx.count_vars(str(prefix))
|