Jump to content

Exporting OOP class


Sorata_Kanda

Recommended Posts

Hello everyone,

I stumbled across several topics about exporting OOP stuff.

I'm wondering if you're still not able to export OOP classes as the date of creation was 2 years ago and things might have changed.

Just got somewhat familiar with OOP in MTA. Sadly, if you're not able to export those classes, it is somewhat useless to implement stuff with OO style

Thanks in advance!

Link to comment
  • Moderators

@Sorata_Kanda

The value [function] is a part of a class. Functions can't leave their resource environment. So it is impossible to export them while they are loaded.

 

But you can send them over as unloaded code:

local exportedFunctionValue = "Airplane = {} function Airplane:fly () end"


loadstring(exportedFunctionValue)()

 

  • Like 1
Link to comment

@Sorata_Kanda you can't pass any sort of functions or metatables unfortunately. However as IIYAMA said you can use loadstring to inject code into your scripts. I wrote this a while back:

function load()
	return [[
		function import(name)
			if type(name) ~= 'string' then
				error("bad arg #1 to 'import' (string expected)", 3)
			end

			local content = exports.import:getFileContents(name)

			if not content then
				error("can't import '"..name.."' (doesn't exist)", 2)
			end

			return loadstring('return function() '..content..' end')()()
		end
	]]
end

function getFileContents(name)
	if not name then return end
	local path = 'exports/'..name..'.lua'
	if fileExists(path) then
		local f = fileOpen(path)
		local content = f:read(f.size)
		f:close()
		return content
	end
	return false
end

If you put this in a resource called "import" then you'd use it like this:

loadstring(import.exports:load())()

local utils = import('utils')

iprint(utils)

This loads files directly into a variable in your script. Ofcourse you can easily modify this to load files from different resources.

Also in said files you will have to return the class or function or whatever you need to return just like real modules.

  • Like 1
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...