Print function has effect to code behaviour (SOLVED)

There is a small project with DirtyLarry library (by @sven) using.
It contains line in file “main.gui_script”:
> 24 --print(self.fields.value)

If you will uncomment the line:
0. Run project

  1. Press gui Button
  2. Input field will contain: “1234” (with active color)

If you will comment the line:
0. Run project

  1. Press gui Button
  2. Input field will contain: “No Text” (with inactive color)

What is going on? Why?

DGTest.zip (13.1 KB)

Windows 7, Editor v1.2.99 (both 1 and 2)

1 Like

Ok, this has a very logical explanation. I will post the script here for everyones benefit:

local DirtyLarry = require "dirtylarry/dirtylarry"

local function on_menu_button_pressed()
	local root = gui.get_node('root')
	local is_enabled = gui.is_enabled(root)
	gui.set_enabled(root, not is_enabled)
end

function init(self)
	msg.post('#', 'acquire_input_focus')
	gui.set_enabled(gui.get_node('root'), false)
end

function on_message(self, message_id, message, sender)
	if message_id == hash('set_this') then
		self.fields = {
			value = message.value,
		}
		gui.set_text(gui.get_node('input/content'), tostring(self.fields.value))
	end
end

function on_input(self, action_id, action)
	--print(self.fields.value)
	local v = DirtyLarry:input('input', action_id, action, gui.KEYBOARD_TYPE_NUMBER_PAD, 'No Text')
	DirtyLarry:button('button', action_id, action, on_menu_button_pressed)
end

self.fields will be nil until a set_this message has been received. on_input will be called every time your script receives input. This input can be a mouse click, a key press, game pad button OR mouse movement (depending on your game input bindings ofc).

This means that as soon as the script is running and you move the mouse you will start to get calls to on_input. I’m guessing that self.fields is nil at that point meaning that the on_input function will crash on the print(self.fields.value) line. It crashes since since you are trying to read the value from something that is nil. The crash on the first line will result in subsequent statements not being executed and the input field will not be given the “No text” default value set by Dirty Larry.

The solution is either to set self.fields = {} in init() or check if self.fields is nil before attempting to read values from it.

3 Likes

It looks, you are right.
Thanks!

BTW, there should be errors in the console that would indicate this as well.

  1. Error is only one and it’s hidden by another log spam.
  2. I did not completely understand library logic and thought, that the crash does not have an effect. Now I get it: I can set my own value to input field only before first call of on_input function
  3. Some not-full-rebuild stuff (: