Browse Source

Change type registration to use JSON

master
chrisgregan 9 years ago
parent
commit
eccd1fecf5
  1. 81
      Assets/Fungus/FungusLua/Resources/Types/FungusTypes.txt
  2. 130
      Assets/Fungus/FungusLua/Resources/Types/UnityTypes.txt
  3. 12
      Assets/Fungus/FungusLua/Scripts/LuaEnvironment.cs
  4. 50
      Assets/Fungus/FungusLua/Scripts/LuaUtils.cs
  5. 9
      Assets/Fungus/FungusLua/Thirdparty/JSON.meta
  6. 1115
      Assets/Fungus/FungusLua/Thirdparty/JSON/JSONObject.cs
  7. 2
      Assets/Fungus/FungusLua/Thirdparty/JSON/JSONObject.cs.meta
  8. 188
      Assets/Fungus/FungusLua/Thirdparty/JSON/readme.txt
  9. 2
      Assets/Fungus/FungusLua/Thirdparty/JSON/readme.txt.meta
  10. 166
      Assets/Tests/Lua/LuaEnvironmentTests.unity

81
Assets/Fungus/FungusLua/Resources/Types/FungusTypes.txt

@ -1,43 +1,38 @@
# List of c# types to register with MoonSharp {
# LuaBindings usually takes care of registering the types of bound objects, but in some "registerTypes" : [
# cases you'll need to register a type manually by adding it to this list. "Fungus.AnimatorVariable",
# You can also register types using MoonSharp's UserData class in the Awake method of a component. "Fungus.AudioSourceVariable",
# To register an extension type, add the E: prefix "Fungus.Block",
# If the type is defined in the main assembly then you can just use namespace.typename "Fungus.BooleanVariable",
# If the type is defined in any other assembly you need to use the full assembly qualified type name. "Fungus.Character",
"Fungus.ColorVariable",
Fungus.AnimatorVariable "Fungus.Command",
Fungus.AudioSourceVariable "Fungus.CommandInfoAttribute",
Fungus.Block "Fungus.FacingDirection",
Fungus.BooleanVariable "Fungus.FloatVariable",
Fungus.Character "Fungus.Flowchart",
Fungus.ColorVariable "Fungus.FungusPrefs",
Fungus.Command "Fungus.LuaEnvironment",
Fungus.CommandInfoAttribute "Fungus.LuaUtils",
Fungus.FacingDirection "Fungus.GameObjectVariable",
Fungus.FloatVariable "Fungus.IntegerVariable",
Fungus.Flowchart "Fungus.Label",
Fungus.FungusPrefs "Fungus.MaterialVariable",
Fungus.LuaEnvironment "Fungus.MenuDialog",
Fungus.LuaUtils "Fungus.ObjectVariable",
Fungus.GameObjectVariable "Fungus.PODTypeFactory",
Fungus.IntegerVariable "Fungus.PortraitState",
Fungus.Label "Fungus.SayDialog",
Fungus.MaterialVariable "Fungus.SpriteVariable",
Fungus.MenuDialog "Fungus.StringVariable",
Fungus.ObjectVariable "Fungus.Task",
Fungus.PODTypeFactory "Fungus.TextureVariable",
Fungus.PortraitState "Fungus.TransformVariable",
Fungus.SayDialog "Fungus.Variable",
Fungus.SpriteVariable "Fungus.Vector2Variable",
Fungus.StringVariable "Fungus.Vector3Variable"
Fungus.Task ],
Fungus.TextureVariable "extensionTypes" : [
Fungus.TransformVariable "Fungus.LuaExtensions"
Fungus.Variable ]
Fungus.Vector2Variable }
Fungus.Vector3Variable
# Extension types
E:Fungus.LuaExtensions

130
Assets/Fungus/FungusLua/Resources/Types/UnityTypes.txt

@ -1,67 +1,63 @@
# List of c# types to register with MoonSharp {
# LuaBindings usually takes care of registering the types of bound objects, but in some "registerTypes" : [
# cases you'll need to register a type manually by adding it to this list. "System.Action, System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
# You can also register types using MoonSharp's UserData class in the Awake method of a component. "System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
# To register an extension type, add the E: prefix "System.Collections.IEnumerator, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
# If the type is defined in the main assembly then you can just use namespace.typename "System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
# If the type is defined in any other assembly you need to use the full assembly qualified type name. "System.IntPtr, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"System.Single, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
System.Action, System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 "System.Type, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 "System.UInt32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
System.Collections.IEnumerator, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 "UnityEngine.AudioClip, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 "UnityEngine.AudioClipLoadType, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
System.IntPtr, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 "UnityEngine.AudioDataLoadState, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
System.Single, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 "UnityEngine.AudioSource, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
System.Type, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 "UnityEngine.Bounds, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
System.UInt32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 "UnityEngine.Canvas, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.AudioClip, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Color, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.AudioClipLoadType, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Component, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.AudioDataLoadState, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.ComputeBuffer, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.AudioSource, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Coroutine, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Bounds, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.EventSystems.BaseEventData, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Canvas, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.EventSystems.PointerEventData, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Color, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Font, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Component, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.FontStyle, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.ComputeBuffer, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.GameObject, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Coroutine, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.HorizontalWrapMode, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.EventSystems.BaseEventData, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Material, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.EventSystems.PointerEventData, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.MaterialGlobalIlluminationFlags, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Font, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Matrix4x4, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.FontStyle, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.MonoBehaviour, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.GameObject, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Object, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.HorizontalWrapMode, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.PrimitiveType, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Material, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Quaternion, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.MaterialGlobalIlluminationFlags, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Rect, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Matrix4x4, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.RectTransform, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.MonoBehaviour, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.SceneManagement.Scene, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Object, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.ScriptableObject, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.PrimitiveType, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.SendMessageOptions, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Quaternion, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Shader, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Rect, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Sprite, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.RectTransform, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.SpriteMeshType, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.SceneManagement.Scene, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.SpritePackingMode, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.ScriptableObject, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.SpritePackingRotation, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.SendMessageOptions, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.TextAnchor, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Shader, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.TextGenerationSettings, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Sprite, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.TextGenerator, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.SpriteMeshType, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Texture, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.SpritePackingMode, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Texture2D, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.SpritePackingRotation, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.TextureFormat, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.TextAnchor, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Time, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.TextGenerationSettings, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Transform, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.TextGenerator, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.UI.Button, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Texture, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.UI.Image, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Texture2D, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.UI.Slider, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.TextureFormat, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.UI.Text, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Time, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Vector2, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.Transform, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Vector3, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.UI.Button, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.Vector4, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
UnityEngine.UI.Image, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null "UnityEngine.VerticalWrapMode, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
UnityEngine.UI.Slider, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null ],
UnityEngine.UI.Text, UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null "extensionTypes" : [
UnityEngine.Vector2, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null ]
UnityEngine.Vector3, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null }
UnityEngine.Vector4, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
UnityEngine.VerticalWrapMode, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
# Extension types

12
Assets/Fungus/FungusLua/Scripts/LuaEnvironment.cs

@ -167,17 +167,9 @@ namespace Fungus
/// <summary> /// <summary>
/// Register a type given it's assembly qualified name. /// Register a type given it's assembly qualified name.
/// </summary> /// </summary>
public static void RegisterType(string typeName) public static void RegisterType(string typeName, bool extensionType = false)
{ {
bool extensionType = false; System.Type t = System.Type.GetType(typeName);
string registerName = typeName;
if (typeName.StartsWith("E:"))
{
extensionType = true;
registerName = registerName.Substring(2);
}
System.Type t = System.Type.GetType(registerName);
if (t == null) if (t == null)
{ {
UnityEngine.Debug.LogWarning("Type not found: " + typeName); UnityEngine.Debug.LogWarning("Type not found: " + typeName);

50
Assets/Fungus/FungusLua/Scripts/LuaUtils.cs

@ -112,18 +112,30 @@ namespace Fungus
continue; continue;
} }
char[] separators = { '\r', '\n' }; // Parse JSON file
foreach (string typeName in textFile.text.Split(separators, StringSplitOptions.RemoveEmptyEntries)) JSONObject jsonObject = new JSONObject(textFile.text);
{ if (jsonObject == null ||
// Skip comments and empty lines jsonObject.type != JSONObject.Type.OBJECT)
if (typeName.StartsWith("#") || typeName.Trim() == "")
{ {
UnityEngine.Debug.LogError("Error parsing JSON file " + textFile.name);
continue; continue;
} }
// Register types with MoonSharp
JSONObject registerTypesArray = jsonObject.GetField("registerTypes");
if (registerTypesArray != null &&
registerTypesArray.type == JSONObject.Type.ARRAY)
{
foreach (JSONObject entry in registerTypesArray.list)
{
if (entry != null &&
entry.type == JSONObject.Type.STRING)
{
string typeName = entry.str.Trim();
// Don't register fungus types if the Fungus library is not present // Don't register fungus types if the Fungus library is not present
if (!isFungusInstalled && if (!isFungusInstalled &&
typeName.Contains("Fungus.")) typeName.StartsWith("Fungus."))
{ {
continue; continue;
} }
@ -133,6 +145,32 @@ namespace Fungus
} }
} }
// Register extension types with MoonSharp
JSONObject extensionTypesArray = jsonObject.GetField("extensionTypes");
if (extensionTypesArray != null &&
extensionTypesArray.type == JSONObject.Type.ARRAY)
{
foreach (JSONObject entry in extensionTypesArray.list)
{
if (entry != null &&
entry.type == JSONObject.Type.STRING)
{
string typeName = entry.str.Trim();
// Don't register fungus types if the Fungus library is not present
if (!isFungusInstalled &&
typeName.StartsWith("Fungus."))
{
continue;
}
LuaEnvironment.RegisterType(typeName, true);
}
}
}
}
}
/// <summary> /// <summary>
/// Binds all gameobjects and components defined in scene LuaBindings to the global table. /// Binds all gameobjects and components defined in scene LuaBindings to the global table.
/// </summary> /// </summary>

9
Assets/Fungus/FungusLua/Thirdparty/JSON.meta vendored

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 0457c4629ab644fa2943c7447039a533
folderAsset: yes
timeCreated: 1460471395
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

1115
Assets/Fungus/FungusLua/Thirdparty/JSON/JSONObject.cs vendored

File diff suppressed because it is too large Load Diff

2
Assets/Fungus/FungusLua/Thirdparty/JSON/JSONObject.cs.meta vendored

@ -0,0 +1,2 @@
fileFormatVersion: 1
guid: f71819923b555d14ab64ae2044718de9

188
Assets/Fungus/FungusLua/Thirdparty/JSON/readme.txt vendored

@ -0,0 +1,188 @@
==Author==
[mailto:schoen@defectivestudios.com Matt Schoen] of [http://www.defectivestudios.com Defective Studios]
==Download==
[[Media:JSONObject.zip|Download JSONObject.zip]]
= Intro =
I came across the need to send structured data to and from a server on one of my projects, and figured it would be worth my while to use JSON. When I looked into the issue, I tried a few of the C# implementations listed on [http://json.org json.org], but found them to be too complicated to work with and expand upon. So, I've written a very simple JSONObject class, which can be generically used to encode/decode data into a simple container. This page assumes that you know what JSON is, and how it works. It's rather simple, just go to json.org for a visual description of the encoding format.
As an aside, this class is pretty central to the [[AssetCloud]] content management system, from Defective Studios.
Update: The code has been updated to version 1.4 to incorporate user-submitted patches and bug reports. This fixes issues dealing with whitespace in the format, as well as empty arrays and objects, and escaped quotes within strings.
= Usage =
Users should not have to modify the JSONObject class themselves, and must follow the very simple proceedures outlined below:
Sample data (in JSON format):
<nowiki>
{
"TestObject": {
"SomeText": "Blah",
"SomeObject": {
"SomeNumber": 42,
"SomeBool": true,
"SomeNull": null
},
"SomeEmptyObject": { },
"SomeEmptyArray": [ ],
"EmbeddedObject": "{\"field\":\"Value with \\\"escaped quotes\\\"\"}"
}
}</nowiki>
= Features =
*Decode JSON-formatted strings into a usable data structure
*Encode structured data into a JSON-formatted string
*Interoperable with Dictionary and WWWForm
*Optimized parse/stringify functions -- minimal (unavoidable) garbage creation
*Asynchronous stringify function for serializing lots of data without frame drops
*MaxDepth parsing will skip over nested data that you don't need
*Special (non-compliant) "Baked" object type can store stringified data within parsed objects
*Copy to new JSONObject
*Merge with another JSONObject (experimental)
*Random access (with [int] or [string])
*ToString() returns JSON data with optional "pretty" flag to include newlines and tabs
*Switch between double and float for numeric storage depending on level of precision needed (and to ensure that numbers are parsed/stringified correctly)
*Supports Infinity and NaN values
*JSONTemplates static class provides serialization functions for common classes like Vector3, Matrix4x4
*Object pool implementation (experimental)
*Handy JSONChecker window to test parsing on sample data
It should be pretty obvious what this parser can and cannot do. If anyone reading this is a JSON buff (is there such a thing?) please feel free to expand and modify the parser to be more compliant. Currently I am using the .NET System.Convert namespace functions for parsing the data itself. It parses strings and numbers, which was all that I needed of it, but unless the formatting is supported by System.Convert, it may not incorporate all proper JSON strings. Also, having never written a JSON parser before, I don't doubt that I could improve the efficiency or correctness of the parser. It serves my purpose, and hopefully will help you with your project! Let me know if you make any improvements :)
Also, you JSON buffs (really, who would admit to being a JSON buff...) might also notice from my feature list that this thing isn't exactly to specifications. Here is where it differs:
*"a string" is considered valid JSON. There is an optional "strict" parameter to the parser which will bomb out on such input, in case that matters to you.
*The "Baked" mode is totally made up.
*The "MaxDepth" parsing is totally made up.
*NaN and Infinity aren't officially supported by JSON ([http://stackoverflow.com/questions/1423081/json-left-out-infinity-and-nan-json-status-in-ecmascript read more] about this issue... I lol'd @ the first comment on the first answer)
*I have no idea about edge cases in my parsing strategy. I have been using this code for about 3 years now and have only had to modify the parser because other people's use cases (still valid JSON) didn't parse correctly. In my experience, anything that this code generates is parsed just fine.
== Encoding ==
Encoding is something of a hard-coded process. This is because I have no idea what your data is! It would be great if this were some sort of interface for taking an entire class and encoding it's number/string fields, but it's not. I've come up with a few clever ways of using loops and/or recursive methods to cut down of the amount of code I have to write when I use this tool, but they're pretty project-specific.
Note: This section used to be WRONG! And now it's OLD! Will update later... this will all still work, but there are now a couple of ways to skin this cat.
<syntaxhighlight lang="csharp">
//Note: your data can only be numbers and strings. This is not a solution for object serialization or anything like that.
JSONObject j = new JSONObject(JSONObject.Type.OBJECT);
//number
j.AddField("field1", 0.5);
//string
j.AddField("field2", "sampletext");
//array
JSONObject arr = new JSONObject(JSONObject.Type.ARRAY);
j.AddField("field3", arr);
arr.Add(1);
arr.Add(2);
arr.Add(3);
string encodedString = j.print();
</syntaxhighlight>
NEW! The constructor, Add, and AddField functions now support a nested delegate structure. This is useful if you need to create a nested JSONObject in a single line. For example:
<syntaxhighlight lang="csharp">
DoRequest(URL, new JSONObject(delegate(JSONObject request) {
request.AddField("sort", delegate(JSONObject sort) {
sort.AddField("_timestamp", "desc");
});
request.AddField("query", new JSONObject(delegate(JSONObject query) {
query.AddField("match_all", JSONObject.obj);
}));
request.AddField("fields", delegate(JSONObject fields) {
fields.Add("_timestamp");
});
}).ToString());
</syntaxhighlight>
== Decoding ==
Decoding is much simpler on the input end, and again, what you do with the JSONObject will vary on a per-project basis. One of the more complicated way to extract the data is with a recursive function, as drafted below. Calling the constructor with a properly formatted JSON string will return the root object (or array) containing all of its children, in one neat reference! The data is in a public ArrayList called list, with a matching key list (called keys!) if the root is an Object. If that's confusing, take a glance over the following code and the print() method in the JSONOBject class. If there is an error in the JSON formatting (or if there's an error with my code!) the debug console will read "improper JSON formatting".
<syntaxhighlight lang="csharp">
string encodedString = "{\"field1\": 0.5,\"field2\": \"sampletext\",\"field3\": [1,2,3]}";
JSONObject j = new JSONObject(encodedString);
accessData(j);
//access data (and print it)
void accessData(JSONObject obj){
switch(obj.type){
case JSONObject.Type.OBJECT:
for(int i = 0; i < obj.list.Count; i++){
string key = (string)obj.keys[i];
JSONObject j = (JSONObject)obj.list[i];
Debug.Log(key);
accessData(j);
}
break;
case JSONObject.Type.ARRAY:
foreach(JSONObject j in obj.list){
accessData(j);
}
break;
case JSONObject.Type.STRING:
Debug.Log(obj.str);
break;
case JSONObject.Type.NUMBER:
Debug.Log(obj.n);
break;
case JSONObject.Type.BOOL:
Debug.Log(obj.b);
break;
case JSONObject.Type.NULL:
Debug.Log("NULL");
break;
}
}
</syntaxhighlight>
NEW! Decoding now also supports a delegate format which will automatically check if a field exists before processing the data, providing an optional parameter for an OnFieldNotFound response. For example:
<syntaxhighlight lang="csharp">
new JSONObject(data);
list.GetField("hits", delegate(JSONObject hits) {
hits.GetField("hits", delegate(JSONObject hits2) {
foreach (JSONObject gameSession in hits2.list) {
Debug.Log(gameSession);
}
});
}, delegate(string name) { //"name" will be equal to the name of the missing field. In this case, "hits"
Debug.LogWarning("no game sessions");
});
</syntaxhighlight>
===Not So New! (O(n)) Random access!===
I've added a string and int [] index to the class, so you can now retrieve data as such (from above):
<syntaxhighlight lang="csharp">
JSONObject arr = obj["field3"];
Debug.log(arr[2].n); //Should ouptut "3"
</syntaxhighlight>
----
---Code omitted from readme---
=Change Log=
==v1.4==
Big update!
*Better GC performance. Enough of that garbage!
**Remaining culprits are internal garbage from StringBuilder.Append/AppendFormat, String.Substring, List.Add/GrowIfNeeded, Single.ToString
*Added asynchronous Stringify function for serializing large amounts of data at runtime without frame drops
*Added Baked type
*Added MaxDepth to parsing function
*Various cleanup refactors recommended by ReSharper
==v1.3.2==
*Added support for NaN
*Added strict mode to fail on purpose for improper formatting. Right now this just means that if the parse string doesn't start with [ or {, it will print a warning and return a null JO.
*Changed infinity and NaN implementation to use float and double instead of Mathf
*Handles empty objects/arrays better
*Added a flag to print and ToString to turn on/off pretty print. The define on top is now an override to system-wide disable
==Earlier Versions==
I'll fill these in later...
[[Category:C Sharp]]
[[Category:Scripts]]
[[Category:Utility]]
[[Category:JSON]]

2
Assets/Fungus/FungusLua/Thirdparty/JSON/readme.txt.meta vendored

@ -0,0 +1,2 @@
fileFormatVersion: 1
guid: 80b692916bec1664098283aa4425e4d8

166
Assets/Tests/Lua/LuaEnvironmentTests.unity

@ -242,6 +242,58 @@ MonoBehaviour:
' '
runAsCoroutine: 1 runAsCoroutine: 1
--- !u!1 &156811089
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 139298, guid: c356764ac08ce4af2806a601a4f1e6e9, type: 2}
m_PrefabInternal: {fileID: 0}
serializedVersion: 4
m_Component:
- 4: {fileID: 156811091}
- 114: {fileID: 156811090}
m_Layer: 0
m_Name: LuaScript
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &156811090
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 11472914, guid: c356764ac08ce4af2806a601a4f1e6e9,
type: 2}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 156811089}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 446caeace65234baaacd52095d24f101, type: 3}
m_Name:
m_EditorClassIdentifier:
executeAfterTime: 1
repeatExecuteTime: 1
repeatEveryTime: 1
executeAfterFrames: 1
repeatExecuteFrame: 1
repeatEveryFrame: 1
hasFailed: 0
executeMethods: 2
luaEnvironment: {fileID: 0}
luaFile: {fileID: 0}
luaScript: pass()
runAsCoroutine: 1
--- !u!4 &156811091
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 449874, guid: c356764ac08ce4af2806a601a4f1e6e9, type: 2}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 156811089}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 1887843215}
m_RootOrder: 1
--- !u!4 &236999594 stripped --- !u!4 &236999594 stripped
Transform: Transform:
m_PrefabParentObject: {fileID: 495584, guid: 49031c561e16d4fcf91c12153f8e0b25, type: 2} m_PrefabParentObject: {fileID: 495584, guid: 49031c561e16d4fcf91c12153f8e0b25, type: 2}
@ -812,6 +864,67 @@ Transform:
m_Children: [] m_Children: []
m_Father: {fileID: 1537199682} m_Father: {fileID: 1537199682}
m_RootOrder: 2 m_RootOrder: 2
--- !u!1 &870653406
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 100640, guid: 49031c561e16d4fcf91c12153f8e0b25, type: 2}
m_PrefabInternal: {fileID: 0}
serializedVersion: 4
m_Component:
- 4: {fileID: 870653407}
- 114: {fileID: 870653409}
- 114: {fileID: 870653408}
m_Layer: 0
m_Name: LuaEnvironment
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &870653407
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 495584, guid: 49031c561e16d4fcf91c12153f8e0b25, type: 2}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 870653406}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 1887843215}
m_RootOrder: 0
--- !u!114 &870653408
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 11486636, guid: 49031c561e16d4fcf91c12153f8e0b25,
type: 2}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 870653406}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c10f0b861365b42b0928858f7b086ff3, type: 3}
m_Name:
m_EditorClassIdentifier:
fungusModule: 0
stringTable: {fileID: 0}
activeLanguage: en
timeScale: -1
registerTypes:
- {fileID: 4900000, guid: 9c3ab7a98d51241bbb499643399fa761, type: 3}
- {fileID: 4900000, guid: 93fddea8208764a2dbb189cc238aed40, type: 3}
--- !u!114 &870653409
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 11493126, guid: 49031c561e16d4fcf91c12153f8e0b25,
type: 2}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 870653406}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: ba19c26c1ba7243d2b57ebc4329cc7c6, type: 3}
m_Name:
m_EditorClassIdentifier:
remoteDebugger: 0
--- !u!1 &1052730009 --- !u!1 &1052730009
GameObject: GameObject:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0
@ -1906,6 +2019,57 @@ Prefab:
Transform: Transform:
m_PrefabParentObject: {fileID: 495584, guid: 49031c561e16d4fcf91c12153f8e0b25, type: 2} m_PrefabParentObject: {fileID: 495584, guid: 49031c561e16d4fcf91c12153f8e0b25, type: 2}
m_PrefabInternal: {fileID: 1855619325} m_PrefabInternal: {fileID: 1855619325}
--- !u!1 &1887843213
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 4
m_Component:
- 4: {fileID: 1887843215}
- 114: {fileID: 1887843214}
m_Layer: 0
m_Name: LuaEnvironmentTest
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &1887843214
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1887843213}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: b1dba0b27b0864740a8720e920aa88c0, type: 3}
m_Name:
m_EditorClassIdentifier:
timeout: 5
ignored: 0
succeedAfterAllAssertionsAreExecuted: 0
expectException: 0
expectedExceptionList:
succeedWhenExceptionIsThrown: 0
includedPlatforms: -1
platformsToIgnore: []
dynamic: 0
dynamicTypeName:
--- !u!4 &1887843215
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1887843213}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 870653407}
- {fileID: 156811091}
m_Father: {fileID: 0}
m_RootOrder: 13
--- !u!1 &1900871524 --- !u!1 &1900871524
GameObject: GameObject:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0
@ -1921,7 +2085,7 @@ GameObject:
m_Icon: {fileID: 0} m_Icon: {fileID: 0}
m_NavMeshLayer: 0 m_NavMeshLayer: 0
m_StaticEditorFlags: 0 m_StaticEditorFlags: 0
m_IsActive: 1 m_IsActive: 0
--- !u!114 &1900871525 --- !u!114 &1900871525
MonoBehaviour: MonoBehaviour:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0

Loading…
Cancel
Save