Jump to content

os.loadAPI without treating it like a class

api computer

2 replies to this topic

#1 Adamski1997

  • Members
  • 8 posts

Posted 03 September 2018 - 09: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.


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


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?

#2 Jummit

  • Members
  • 306 posts
  • LocationJulfander Squad Studio

Posted 03 September 2018 - 01:55 PM

Use require. Require runs the file you give it and returns anything this file returns.
--# the class
return {
	new = function(var)
		--# return the new object
		return {
		   var = var
File loading the class:
--# store the class
local MyClass = require "MyClass"
--# or use it directly
instance = (require "MyClass").new("foo")

Edited by Jummit, 03 September 2018 - 01:57 PM.

#3 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 04 September 2018 - 08: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:


View PostAdamski1997, on 03 September 2018 - 09:37 AM, said:

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".

1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users