Menu
CoddyTech

Validated Conversion

Lesson 34 of 48 in Coddy's GDScript for Lua Developers course.

Lua tonumber returns nil for text it cannot convert, instead of raising an ordinary conversion error. It may accept syntax broader than an API's integer grammar, so conversion alone is not full contract validation. The example requires an optional sign followed by ASCII digits, rejecting suffix junk. GDScript to_int() can be permissive; use is_valid_int() when the full token must be an integer. Decide whether spaces are allowed before trimming. Bounds are a second check after syntax. JSON numbers enter the target driver as floating Variant values, so task APIs explicitly convert bounded integer inputs.

Complete Lua 5.1 comparison. Run main.lua from the directory containing all shown files:

Lua file main.lua:

local text = "42x"
local valid = string.match(text, "^[+-]?[0-9]+$") ~= nil
print(valid and "valid" or "invalid")

Lua output:

invalid

GDScript file main.gd:

extends Node

func _ready() -> void:
	var text: String = "42x"
	print("valid" if text.is_valid_int() else "invalid")

GDScript output:

invalid
challenge icon

Challenge

Easy

Input is one text token. Accept only String.is_valid_int(), with no trimming, then return twice the parsed number. Otherwise return invalid. Valid numeric magnitudes are at most 10000.

Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.

Your code goes in exercise.gd. The supplied main.gd cannot be edited. Keep each class_name type in its named file.

Try it yourself

extends Node

func contract_ok(data: Array) -> bool:

	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for Lua Developers

Practice on your own: Online GDScript compiler