-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathQuickScriptComponent.kt
82 lines (70 loc) · 2.29 KB
/
QuickScriptComponent.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package me.anno.lua
import me.anno.Time
import me.anno.ecs.Component
import me.anno.ecs.annotations.DebugAction
import me.anno.ecs.annotations.Type
import me.anno.ecs.components.player.LocalPlayer
import me.anno.ecs.prefab.PrefabSaveable
import me.anno.ecs.systems.OnUpdate
import me.anno.lua.ScriptComponent.Companion.getFunction
import me.anno.lua.ScriptComponent.Companion.toLua
import org.apache.logging.log4j.LogManager
import org.luaj.vm2.LuaError
import org.luaj.vm2.LuaValue
@Suppress("MemberVisibilityCanBePrivate")
open class QuickScriptComponent : Component(), OnUpdate {
@Type("Lua/Code")
var createScript = ""
@Type("Lua/Code")
var updateScript = ""
@Type("Lua/Code")
var destroyScript = ""
@DebugAction
override fun onCreate() {
super.onCreate()
callFunction(createScript)
}
@DebugAction
override fun onUpdate() {
callFunction(updateScript)
}
@DebugAction
override fun destroy() {
super.destroy()
callFunction(destroyScript)
}
override fun copyInto(dst: PrefabSaveable) {
super.copyInto(dst)
if (dst !is QuickScriptComponent) return
dst.createScript = createScript
dst.updateScript = updateScript
dst.destroyScript = destroyScript
}
fun getFunction1(code: String, init: ((scope: LuaValue) -> Unit)? = null): LuaValue {
return getFunction(code) { globals ->
globals.set("entity", entity.toLua())
globals.set("transform", entity?.transform.toLua())
globals.set("parent", parent.toLua())
globals.set("dt", LuaValue.valueOf(Time.deltaTime))
globals.set("t", LuaValue.valueOf(Time.gameTime))
globals.set("player", LocalPlayer.currentLocalPlayer.toLua())
init?.invoke(globals)
}
}
fun callFunction(code: String) {
val func = getFunction1(code) {}
if (func.isfunction()) {
try {
val value = func.call()
if (!value.isnil()) {
LOGGER.info("Return value: {}", value)
}
} catch (e: LuaError) {
LOGGER.warn(e)
}
}
}
companion object {
private val LOGGER = LogManager.getLogger(QuickScriptComponent::class)
}
}