Перейти к содержимому
  • 0
HeroBrine1st

Таблица не воссоздаётся из строки

Вопрос

При запуске скачивает файл, добавляет его в таблицу типа {"я еще так думаю"} (да, текст в таблице - уже не пример, а сама таблица - да)

https://github.com/HeroBrine1st/OpenComputers/blob/master/MCBios/applications.txt - сама таблица. т.к. загрузка идет как  {функция}, то создавать единую таблицу, объединяющую все, в файле не нужно.

 

 

local EEPROMLabel = "EEPROM (MС BIOS)"
local component = require("component")
local computer = require("computer")
local fs = require("filesystem")
local internet = require("internet")
local serialization = require("serialization")
local shell = require("shell")
local EEPROMCode
local GitHubUrl = "https://raw.githubusercontent.com/"

local function internetRequest(url)
  local success, response = pcall(component.internet.request, url)
  if success then
    local responseData = ""
    while true do
      local data, responseChunk = response.read()
      if data then
        responseData = responseData .. data
      else
        if responseChunk then
         return false, responseChunk
        else
      return true, responseData
    end
    end
    end
  else
    return false, reason
  end
end
 local write = io.write
local read = io.read



local function getFromGitHub(url,filepath)
 local success, reason = internetRequest(url)
 if success then
   fs.makeDirectory(fs.path(filepath) or "")
   fs.remove(filepath)
   local file = io.open(filepath, "w")
   file:write(reason)
   file:close()
   return reason
 else
   error("error")
 end
end

local applications = {}
write("Downloading file list... \n")
applications = {getFromGitHub(GitHubUrl .. "HeroBrine1st/OpenComputers/master/MCBios/applications.txt", "/MCBios/applications.txt")}
print(applications)
print(#applications)
local i
for i = 1, #applications do
write("Downloading \"" .. applications[i].name .. "\"\n")
getFromGitHub(GitHubUrl .. applications[i].url, applications[i].name)
end



local f = io.open("/MCBios/EEPROMCode.lua","r")
local success, reason = f:read(4096)
f:close()
if success then
EEPROMCode = success
else
error(reason)
end



local computer = require("computer")
local shell = require("shell")

local options



local eeprom


 write("Insert the EEPROM you would like to flash.\n")
 write("When ready to write, type `y` to confirm.\n")
  local result = read()
  if not result or result == "" or result:sub(1, 1):lower() == "y" then
    eeprom = component.getPrimary("eeprom")
    write("Beginning to flash EEPROM.\n")
    write("Flashing EEPROM " .. eeprom.address .. ".\n")
    write("Please do NOT power down or restart your computer during this operation!\n")
    local uptime = computer.uptime()
    write(eeprom.set(EEPROMCode .. "\n"))
   	local time = computer.uptime() - uptime
   	write("OKAY. Time: " .. time .. "\n")
   	local uptimes = computer.uptime()
   	write("Set label to '" .. EEPROMLabel .. "'\n")
   	eeprom.setLabel(EEPROMLabel)
   	local timess = computer.uptime() - uptimes
    write("OKAY. Time: " .. timess .. "\n")
    local uptimess = computer.uptime()
    write("Clear data \n")
    eeprom.setData("nil")
    local timesss = computer.uptime() - uptimess
    write("OKAY. Time: " .. timesss .. "\n")
   	local times = computer.uptime() - uptime
    options = true
    write("Finished. Time: " .. times .. "\n")
  end
if options then
  write("Reboot now? [Y/n] ")
  local result = read()
  if not result or result == "" or result:sub(1, 1):lower() == "y" then
    write("\nRebooting now!\n")
    computer.shutdown(true)
  end
end

write("Returning to shell.\n")

 

 

 

Код ошибки на скриншоте.


дублируются еще эти темы, блин...

post-19680-0-52067000-1475252211_thumb.png

post-19680-0-58075100-1475252294_thumb.png

Изменено пользователем Alex

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

Рекомендуемые сообщения

Библиотеку serialization ты подключил, но не юзаешь.

Выведи содержимое твоей таблицы на консоль и сам увидишь.

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

@Tororo, короче надо через string.gsub убрать все переносы и добавить в начале через пробел return, затем полученную строку пропустить через load и pcall. много времени прошло, я уже и забыл про эту тему)

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

 

AfcHXRH.png

 

Изменено пользователем Alex

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

...

зато ОЗУ не тратится) serilization в озу много весит

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

зато ОЗУ не тратится) serilization в озу много весит

 

Осталось замерить, сколько жрёт pcall и load.

Ну и вырезание gsub'ами.

Изменено пользователем Totoro

Поделиться сообщением


Ссылка на сообщение
Поделиться на других сайтах

Присоединяйтесь к обсуждению

Вы можете написать сейчас и зарегистрироваться позже. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.

Гость
Ответить на вопрос...

×   Вы вставили отформатированное содержимое.   Удалить форматирование

  Разрешено использовать не более 75 эмодзи.

×   Ваша ссылка была автоматически встроена.   Отобразить как ссылку

×   Ваш предыдущий контент был восстановлен.   Очистить редактор

×   Вы не можете вставлять изображения напрямую. Загружайте или вставляйте изображения по ссылке.


×
×
  • Создать...