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

os.loadAPI without treating it like a class

Started by Adamski1997, 03 September 2018 - 08:37 AM
Adamski1997 #1
Posted 03 September 2018 - 10:37 AM
When you use os.loadAPI all global functions and variables are loaded in as if they are part of the API class e.g.


os.loadAPI("myAPI")
print(myAPI.myVariable)

I am creating an Object Oriented application where I define classes in separate files. The syntax for this in computercraft gets pretty unwieldy:


os.loadAPI("MyClass")
MyClass.MyClass:new()

Since each file contains only that class naming it to something different makes no sense.

My question is can I import MyClass directly to avoid the extra verbosity? Something similar to:


from MyClass import MyClass

in python (for those of you who know it).

Is this possible?
Jummit #2
Posted 03 September 2018 - 02:55 PM
Use require. Require runs the file you give it and returns anything this file returns.
MyClass.lua:

--# the class
return {
	new = function(var)
		--# return the new object
		return {
		   var = var
		}
	end
}
File loading the class:

--# store the class
local MyClass = require "MyClass"
--# or use it directly
instance = (require "MyClass").new("foo")
Edited on 03 September 2018 - 12:57 PM
Bomb Bloke #3
Posted 04 September 2018 - 09:12 AM
Alternatively, just don't define an additional MyClass table within your MyClass file. I'm not sure why you're doing that in the first place, given that you appear to understand that os.loadAPI() is already going to build such a table for you.

If you do want to use "require" instead, bear in mind that it's not present in ComputerCraft builds prior to v1.80. There are a few downloads available around the place if you want to add it in, though - for eg:

http://www.computercraft.info/forums2/index.php?/topic/24015-cc-require-standards-compatible-require-for-computercraft/

When you use os.loadAPI all global functions and variables are loaded in as if they are part of the API class

Just to be sure you that you are clear on this: a ComputerCraft API isn't a class, and strictly speaking, Lua doesn't have anything that is the same as a class. APIs, libraries, classes, whatever - whenever we want to group stuff together, all we're really doing is "dumping it into a table".