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

Convert String to Table Name

Started by MagicCraftMaster, 24 July 2016 - 04:05 PM
MagicCraftMaster #1
Posted 24 July 2016 - 06:05 PM
I am creating an API/Program that takes a file reads it, creates a raw table of every line it read and creates empty tables with names inside the raw table. For example if raw[14] equaled "Commands" I want it to generate a table with that as the name. How can I achieve this? I thank anybody who can help. =)
powerboat9 #2
Posted 24 July 2016 - 06:32 PM
If you set the variable "line" (without quotes) to the value of the line, do:

_G[line] = {}

Because _G is a table representing all the global variables
MagicCraftMaster #3
Posted 24 July 2016 - 07:48 PM
If you set the variable "line" (without quotes) to the value of the line, do:

_G[line] = {}

Because _G is a table representing all the global variables
Thanks for the help!
Edited on 24 July 2016 - 05:50 PM
KingofGamesYami #4
Posted 24 July 2016 - 07:54 PM
It sounds like some of the error message is getting lost. Here's my two cents on the original problem:

- Yes, you can make a table in _G named "Commands". But what is the purpose of that table? And how / why will you access it later?
- Putting any variables in _G is bad practice, as they persist until reboot. What if one of the lines was "os", and you later wanted to use a function in the os API? You can't, because you overwrite the pointer. Instead, add it to your own table, local to your program.

local tStuff = {}

tStuff[ raw[ 14 ] ] = {}
Sewbacca #5
Posted 24 July 2016 - 07:55 PM
I think you want to return the table like this:

<API name here>.<API function name here> = function(...)
  <CODE>
  return res
end
So you don't need to set the name. You can use it like this:
local dataFile = <API name here>.<API function name here>(…)
If you want to return a directory, you can save the name of the files as the keys of the table:
{
startup = {…}
[newFile] = {…}
}

You can add the files like this:


<API name here>.<API function name here> = function(...)
  <get the files of the directory and iterate them>
  for ... do
    ...
    directory[name] = data
    ...
  end
  ...
  return directory
end

I think you want to return the table like this:

<API name here>.<API function name here> = function(...)
  <CODE>
  return res
end
So you don't need to set the name. You can use it like this:
local dataFile = <API name here>.<API function name here>(…)
If you want to return a directory, you can save the name of the files as the keys of the table:
{
startup = {…}
[newFile] = {…}
}

You can add the files like this:


<API name here>.<API function name here> = function(...)
  <get the files of the directory and iterate them>
  for ... do
    ...
    directory[name] = data
    ...
  end
  ...
  return directory
end