This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
snow9590's profile picture

How to Return unique table from loaded API

Started by snow9590, 12 November 2016 - 05:12 AM
snow9590 #1
Posted 12 November 2016 - 06:12 AM
– obj.lua
function new(array)
	return {array = array}
end
– test.lua
os.loadAPI('obj.lua')

arr1 = {1,2,3}
arr2 = {4,5,6}

obj1 = obj.new(arr1)
obj2 = obj.new(arr2)

print(obj1.array[1])	-- prints: 4

My problem is that when I print from the array in obj1, it is actually referencing obj2's array. Ideally this would print 1 instead of 4.
Is it not possible to return a unique table instance from an api function call, or am I just missing some syntax somewhere?
Any help is much appreciated!
Bomb Bloke #2
Posted 12 November 2016 - 01:50 PM
That code should crash as soon as you attempt to call "obj.new"; that function isn't defined anywhere here. You'd need to call _G["obj.lua"].new() instead, due to your placement of a period within the API's filename.

If an "obj.new" does exist, then it would've been a part of a different API which you loaded prior to running this script. Presumably its behaviour is different to the API you've posted here, hence leading to the unexpected result.
Edited on 12 November 2016 - 12:52 PM
snow9590 #3
Posted 14 November 2016 - 04:28 AM
Thanks you! That makes so much more sense. Really appreciate the help!