TypeScriptToLua icon indicating copy to clipboard operation
TypeScriptToLua copied to clipboard

JSON.stringify

Open virtualhu opened this issue 5 years ago • 5 comments

JSON.stringify(obj) be translate to JSON:stringify(obj) but there is no define for JSON in lua. how can i deal with JSON? thanks!

virtualhu avatar Jun 04 '19 07:06 virtualhu

We don't have a JSON implementation in lib yet, but it would be nice to, so marking it as a feature request. For now you can use any lua json library and just write a declaration file for it.

ark120202 avatar Jun 12 '19 03:06 ark120202

You could also write a little adapter with signature JSON:stringify which redirects the call to your JSON library of choice. I meant to write up an example for this a while ago but forgot.

Perryvw avatar Jun 12 '19 12:06 Perryvw

I see a two probelms with this, if we insert a pure lua json lib the same way we inline other lualib features we end up with 100 or more loc for every file that calls a JSON method.

Also this should definitely be optional, since pure lua JSON libs are really slow compared to c implementations CJSON.

lolleko avatar Aug 09 '19 09:08 lolleko

I see a two probelms with this, if we insert a pure lua json lib the same way we inline other lualib features we end up with 100 or more loc for every file that calls a JSON method.

That would be an issue with all huge libs as well, like Promise. In #653 I'm considering dropping inline lualib support in favor of bundling. For now I think at least we should make importing default.

Also this should definitely be optional, since pure lua JSON libs are really slow compared to c implementations CJSON.

I think only minor part of users would be able to use native modules (I don't know any environments (except command-line Lua) that support it). As a part of #653 we'll be able to support lib plugins, like:

const cjsonPlugin: TranspilerPlugin = {
	builtins: [
		{
			pattern: {
				priority: 10,
				kind: BuiltinPatternKind.FunctionSignature,
				baseType: "JSON",
				property: "stringify",
			},
			replacement: {
				kind: BuiltinReplacementKind.Import,
				path: "lua-cjson",
				name: "stringify",
			},
		},
	]
};

ark120202 avatar Aug 09 '19 11:08 ark120202

You could also write a little adapter with signature JSON:stringify which redirects the call to your JSON library of choice. I meant to write up an example for this a while ago but forgot.

The application I'm writing this for has an implementation for JSON - however, typescript complains that I can't overwrite it.

node_modules/typescript/lib/lib.es5.d.ts:1160:13 - error TS2300: Duplicate identifier 'JSON'.

stevenlafl avatar Apr 14 '23 19:04 stevenlafl