Programmatically compiling into GDScript?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By nationality

Suppose I want to make an external level editor for a game. I want the creator to be able to script triggers using a code editor, but using commands that are relevant to the engine to reduce the complexity for users. e.g.

Trigger:
	if x == y:
		Effect

The editor’s compiler will then translate this into something that gdscript could understand, example:

func trigger():
	if x == y:
		return true

How do I then programmatically compile this into a working script? Is there any documentation for doing something like this?

:bust_in_silhouette: Reply From: aXu_AP

I think there is not function to run scripts from strings, but you can load scripts at runtime. Combine this with ability to write file…
Following seems to work:

func _ready() -> void:
	var script = """
extends Node
func _ready():
	print("Hello World!")
"""
	var file = File.new()
	file.open("user://custom_object.gd", File.WRITE)
	file.store_string(script)
	file.close()
	
	var custom_object = load("user://custom_object.gd").new()
	add_child(custom_object)

However, big disclaimer in this! User might be able to intercept this and make arbitrary code run!