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

os.loadAPI with odd files

Started by theoriginalbit, 28 January 2013 - 08:04 PM
theoriginalbit #1
Posted 28 January 2013 - 09:04 PM
Uggghhh over this problem :P/>

I have a file
".support/progName/prog-name.txt"
when using os.loadAPI what identifier is it loaded under? o.O
i figured it would be prog, since prog-name would try to minus name from prog. but it doesn't work.
what am I not thinking of/seeing in my tired haste to get this program updated?
Edited on 28 January 2013 - 08:05 PM
KaoS #2
Posted 28 January 2013 - 09:38 PM
never give it a file extension… it confuses things… try rawget(_G,"prog-name.txt") and rawget(_G,"prog-name")

it probably included the "-" and you just need to access it right
theoriginalbit #3
Posted 28 January 2013 - 10:54 PM
hmmm. I'll give that a go :)/>

I also tried it with dofile and loadfile ( not remembering which was which :P/> ) and I couldn't even get those to work.
KaoS #4
Posted 28 January 2013 - 11:01 PM
I tested it. use

_G["prog-name.txt"].func()

only way I think
ElvishJerricco #5
Posted 10 February 2013 - 10:58 AM
Just an FYI about loadfile in case you didn't figure it out. It doesn't load like an API. It returns a function whose body is the file (hence the ability to do args = { … } in a program). The problem is that by default the environment the file runs in is _G. For those of you that don't know what an environment is, a function's environment is where every global it declares or reads is stored. It's typically bad to keep stuff in _G. To change the environment of the function you get from loadfile, you need to use setfenv(func, env). So basically, this is what you're looking for:


myAPIt = setmetatable({}, {__index = getfenv()}) -- create table for API
myAPIf = loadfile("path") -- load API to function
setfenv(myAPIf, myAPIt) -- make function run in the API environment
myAPIf() -- run the API.

myAPIt.func() -- call a function from the API.

Notice that this doesn't load the API for system use. But that's easy just do _G.myAPI = myAPIt
remiX #6
Posted 10 February 2013 - 12:22 PM
You could move it to be a file with no extension, then load it and then move it again to be with the .txt extension again


fs.move(".support/progName/prog-name.txt",".support/progName/prog-name")
os.loadAPI(".support/progName/prog-name")
fs.move(".support/progName/prog-name", ".support/progName/prog-name.txt")
KaoS #7
Posted 10 February 2013 - 04:11 PM
or even simpler

os.loadAPI(".support/progName/prog-name.txt")
_G.prog-name=_G["prog-name.txt"]
_G["prog-name.txt"]=nil

I prefer to make a custom API loader that allows me to specify the API name and metatable in the API file itself
GopherAtl #8
Posted 10 February 2013 - 11:04 PM
the - won't be allowed in identifiers either. _g.progname=_g["prog-name.txt"]